package com.example.demo.scheduledtask;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.demo.common.Constant;
import com.example.demo.config.ErpConfig;
import com.example.demo.entity.ProcurementDetailsRecode;
import com.example.demo.entity.PurchaseReceiptDetailsRecode;
import com.example.demo.mapper.*;
import com.example.demo.utils.SoapXmlUtil;
import com.example.demo.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO 仓库回写ERP数据
 *
 * @author : Zhang.yt
 * @date : 2023/12/6
 */
@Component
@Slf4j
@DS("wms")
public class WmsPurchaseCallback {

    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;

    @Resource
    private AsyncWorkorderMapper asyncWorkorderMapper;

    @Resource
    private ProcurementDetailsRecodeMapper procurementDetailsRecodeMapper;

    @Resource
    private PurchaseReceiptDetailsRecodeMapper purchaseReceiptDetailsRecodeMapper;

    @Autowired
    private SoapXmlUtil soapXmlUtil;

    @Autowired
    PoMpsinfoMapper poMpsinfoMapper;

    @Resource
    private WmsPurchaseNewMapper wmsPurchaseNewMapper;

    @Resource
    private ErpConfig erpConfig;

//    /**
//     * 采购收货送检单回调-
//     * */
//    //@Transactional(rollbackFor = Exception.class)//测试代码逻辑才能开启事务，测试回调不能开始事务
//    public void purchaseReceiptCallback() {
//        //查询没有回调的数据
//        List<PurchaseNotReceiptVo> purchaseNotReceiptCallback = wmsPurchaseMapper.getPurchaseNotReceiptCallback();
//        List<String> sbillnoList = purchaseNotReceiptCallback.stream().map(PurchaseNotReceiptVo::getPmds055).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(sbillnoList)) {
//            return;
//        }
//        //根据没有回调的数据查询明细
//        List<PurchaseNotReceiptListVo> purchaseNotReceiptListCallback = wmsPurchaseMapper.getPurchaseNotReceiptListCallback(sbillnoList);
//        Map<String, List<PurchaseNotReceiptListVo>> listMap = purchaseNotReceiptListCallback.stream().collect(Collectors.groupingBy(PurchaseNotReceiptListVo::getSlno));
//        //根据采购收货明细获取是采购单号
//        Set<String> purchaseOrderNos = purchaseNotReceiptListCallback.stream().map(PurchaseNotReceiptListVo::getPmdt001).collect(Collectors.toSet());
//        //查询采购单采购详情
//        List<ProcurementDetailsVo> procurementDetailsVos = wmsPurchaseMapper.getProcurementDetailsVo(purchaseOrderNos);
//        //根据采购单分组
//        Map<String, List<ProcurementDetailsVo>> procurementDetailsMap = procurementDetailsVos.stream().collect(Collectors.groupingBy(ProcurementDetailsVo::getPmdldocno));
//
//        //遍历多个采购收货单
//        for (PurchaseNotReceiptVo purchaseNotReceiptVo : purchaseNotReceiptCallback) {
//            purchaseNotReceiptVo.setActionType(Constant.ActionType_I);
//            purchaseNotReceiptVo.setPmdssite(Constant.PMDSSITE_AMA);
//            //获取当前这个采购收货单的详情数据
//            List<PurchaseNotReceiptListVo> purchaseNotReceiptListVos = listMap.get(purchaseNotReceiptVo.getPmds055());
//            //保存回填记录
//            List<ProcurementDetailsRecode> procurementDetailsRecodes = new ArrayList<>();
//            //反填的采购单详情，带上项次
//            List<PurchaseNotReceiptListReq> purchaseNotReceiptListReqs = new ArrayList<>();
//            //遍历采购单收货明细，找到ERP 采购单明细对应的项次
//            for (PurchaseNotReceiptListVo purchaseNotReceiptListVo : purchaseNotReceiptListVos) {
//                //获取这个采购收货单详情对应采购单的采购详情
//                List<ProcurementDetailsVo> procurementDetailsVos1 = procurementDetailsMap.get(purchaseNotReceiptListVo.getPmdt001());
//                //根据物料编号过滤出当前采购收货单的详情物料对应的采购单的采购物料明细，会有多个
//                List<ProcurementDetailsVo> procurementDetailsVoList = procurementDetailsVos1.stream()
//                        .filter(procurementDetailsVo -> procurementDetailsVo.getPmdn001().equals(purchaseNotReceiptListVo.getPmdt006())
//                                && (procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty())).compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
//
//                //取出当前采购收货单的详情物料要回填的数量
//                BigDecimal returnQty = new BigDecimal(purchaseNotReceiptListVo.getPmdt020().toString());
//                //遍历对应的采购单的采购物料明细，给每个项次分配回填数量
//                for (ProcurementDetailsVo procurementDetailsVo : procurementDetailsVoList) {
//                    //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
//                    purchaseNotReceiptVo.setPmds011(procurementDetailsVo.getPmdl005());
//                    //3401	生产性进货报检单; 3410	委外采购报检单
//                    purchaseNotReceiptVo.setPmdsdocno(procurementDetailsVo.getPmdl005() == 1 ? Constant.PMDSDOCNO_3401: Constant.PMDSDOCNO_3410);
//                    //直接创建要回调的采购收货明细详情，数量已以实际各个项次能回填的数量为准
//                    PurchaseNotReceiptListReq bean = BeanUtil.toBean(purchaseNotReceiptListVo, PurchaseNotReceiptListReq.class);
//                    //采购项次
//                    bean.setPmdt002(procurementDetailsVo.getPmdnseq());
//                    //采购项序
//                    bean.setPmdt003(procurementDetailsVo.getPmdoseq1());
//                    //采购分批序
//                    bean.setPmdt004(procurementDetailsVo.getPmdoseq2());
//                    //创建回填记录
//                    ProcurementDetailsRecode procurementDetailsRecode = BeanUtil.toBean(procurementDetailsVo, ProcurementDetailsRecode.class);
//                    //批号
//                    procurementDetailsRecode.setBatchno(purchaseNotReceiptListVo.getPmdt018());
//                    procurementDetailsRecode.setIsDelete(0);
//                    //来源单号是采购收货单号
//                    procurementDetailsRecode.setPmdl008(purchaseNotReceiptVo.getPmds055());
//                    //剩余可回填数量大于等于需要回填数量，该项次回填的是需要回填数量
//                    if((procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty())).compareTo(returnQty) >= 0){
//                        bean.setPmdt020(returnQty);
//                        procurementDetailsRecode.setReturnQty(returnQty);
//                        purchaseNotReceiptListReqs.add(bean);
//                        procurementDetailsRecodes.add(procurementDetailsRecode);
//                        //修改已回填数量加上需要回填数量
//                        procurementDetailsVo.setReturnQty(procurementDetailsVo.getReturnQty().add(returnQty));
//                        //需要回填数量已全部回填，退出循环
//                        break;
//                    }else {
//                        //剩余可回填数量小于需要回填数量，该项次回填的是剩余可回填数量
//                        bean.setPmdt020(procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty()));
//                        procurementDetailsRecode.setReturnQty(procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty()));
//
//                        //需要回填的数量 = 需要回填的数量 - 剩余可回填数量
//                        returnQty = returnQty.subtract(procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty()));
//                        purchaseNotReceiptListReqs.add(bean);
//                        procurementDetailsRecodes.add(procurementDetailsRecode);
//                        //修改已回填数量为该全部已回填
//                        procurementDetailsVo.setReturnQty(procurementDetailsVo.getPmdn007());
//
//                    }
//                }
//            }
//            //-----------测试逻辑代码---------
////            Map<String, String> map =new HashMap<>();
////            map.put("pmdtdocno", "AMA-3401-" + System.currentTimeMillis());
////            XmlResp xmlResp = new XmlResp("0","",map);
////            if(xmlResp.getCode().equals("0")){
////                //更新相应表状态为已下发
////                wmsPurchaseMapper.updatePurchaseReceiptCallback(purchaseNotReceiptVo.getPmds055(),xmlResp.getData().get("pmdtdocno"), 1);
////                for (ProcurementDetailsRecodeVo procurementDetailsRecode : procurementDetailsRecodes) {
////                    procurementDetailsRecode.setReturnNo(xmlResp.getData().get("pmdtdocno"));
////                    //更新采购明细已填数量
////                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
////                    //保存记录
////                    procurementDetailsRecodeVoMapper.insert(procurementDetailsRecode);
////                }
////            }else {
////                //更新相应表状态为已下发
////                wmsPurchaseMapper.updatePurchaseReceiptCallback(purchaseNotReceiptVo.getPmds055(),null, 2);
////            }
//            //-----------测试逻辑代码---------
//
//            String resMessage = soapXmlUtil.getSoapXml("PurchaseGet","pmds_t","pmdt_t",purchaseNotReceiptVo, purchaseNotReceiptListReqs);
//            try {
//                //转换为soap消息
//                MessageFactory msgFactory = MessageFactory.newInstance();
//                SOAPMessage message = msgFactory.createMessage();
//                SOAPPart soapPart = message.getSOAPPart();
//                byte[] buffer = resMessage.getBytes();
//                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
//                StreamSource source = new StreamSource(stream);
//                soapPart.setContent(source);
//                message.writeTo(System.out);
    //log.info(resMessage);
//
//                //发送soap消息，并解析结果
//                String result = soapXmlUtil.sendSoapMessage(message);
//                log.info("soap接口采购收货回调->{}",result);
//                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
//                if(xmlResp.getCode().equals("0")){
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updatePurchaseReceiptCallback(purchaseNotReceiptVo.getPmds055(),xmlResp.getData().get("pmdsdocno"), 1);
//                    for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
//                        procurementDetailsRecode.setReturnNo(xmlResp.getData().get("pmdsdocno"));
//                        //更新采购明细已填数量
//                        wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
//                        //保存记录
//                        procurementDetailsRecodeMapper.insert(procurementDetailsRecode);
//                    }
//                }else {
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updatePurchaseReceiptCallback(purchaseNotReceiptVo.getPmds055(),null, 2);
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//    }
//
//
//    /**
//     * 删除采购收货回调
//     */
//    //@Transactional(rollbackFor = Exception.class) //测试代码逻辑才能开启事务，测试回调不能开始事务
//    public void deletePurchaseReceiptCallback(String orderNo) {
//        DeletePurchaseNotReceiptVo deletePurchaseNotReceiptVo = wmsPurchaseMapper.getDeletePurchaseReceiptCallback(orderNo);
//        if(ObjectUtils.isEmpty(deletePurchaseNotReceiptVo) || StringUtils.isBlank(deletePurchaseNotReceiptVo.getPmdsdocno())){
//            log.info("单据：{}", deletePurchaseNotReceiptVo);
//            throw new RuntimeException("单据不存在或未反写ERP");
//        }
//        //找到未删除回填记录
//        LambdaQueryWrapper<ProcurementDetailsRecode> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ProcurementDetailsRecode::getPmdl008, orderNo)
//                .eq(ProcurementDetailsRecode::getIsDelete, 0);
//        List<ProcurementDetailsRecode> procurementDetailsRecodes = procurementDetailsRecodeMapper.selectList(queryWrapper);
//        //----------测试逻辑代码---------
////        Map<String, String> map =new HashMap<>();
////        map.put("pmdtdocno", "AMA-3401-" + System.currentTimeMillis());
////        XmlResp xmlResp = new XmlResp("0","",map);
////        if(xmlResp.getCode().equals("0")){
////            //更新相应表状态为未下发
////            wmsPurchaseMapper.updatePurchaseReceiptCallback(deletePurchaseNotReceiptVo.getPmds055(), "", 0);
////
////            //找到未删除回填记录
////            LambdaQueryWrapper<ProcurementDetailsRecodeVo> queryWrapper = new LambdaQueryWrapper<>();
////            queryWrapper.eq(ProcurementDetailsRecodeVo::getPmdl008, orderNo)
////                    .eq(ProcurementDetailsRecodeVo::getIsDelete, 0);
////            List<ProcurementDetailsRecodeVo> procurementDetailsRecodeVos = procurementDetailsRecodeVoMapper.selectList(queryWrapper);
////            for (ProcurementDetailsRecodeVo procurementDetailsRecode : procurementDetailsRecodeVos) {
////                //更新采购明细已填数量，已回填数量取反再新增就是减
////                procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
////                wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
////                //删除回填记录
////                procurementDetailsRecodeVoMapper.updateToDelete(procurementDetailsRecode);
////
////            }
////        }
//        //----------测试逻辑代码---------
//        deletePurchaseNotReceiptVo.setActionType(Constant.ActionType_D);
//        ProcurementDetailsRecode procurementDetailsRecodeVo = procurementDetailsRecodes.get(0);
//        //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
//        deletePurchaseNotReceiptVo.setPmds011(procurementDetailsRecodeVo.getPmdl005());
//        String resMessage = soapXmlUtil.getSoapXml("PurchaseGet","pmds_t",deletePurchaseNotReceiptVo);
//        try {
//            //转换为soap消息
//            MessageFactory msgFactory = MessageFactory.newInstance();
//            SOAPMessage message = msgFactory.createMessage();
//            SOAPPart soapPart = message.getSOAPPart();
//            byte[] buffer = resMessage.getBytes();
//            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
//            StreamSource source = new StreamSource(stream);
//            soapPart.setContent(source);
//            message.writeTo(System.out);
    //log.info(resMessage);
//            //log.info("采购入库单回调：{}",resMessage);
//            //发送soap消息，并解析结果
//            String result = soapXmlUtil.sendSoapMessage(message);
//            log.info("删除采购入库单回调结果: {}",result);
//            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
//            if(xmlResp.getCode().equals("0")){
//                //更新相应表状态为未下发
//                wmsPurchaseMapper.updatePurchaseReceiptCallback(deletePurchaseNotReceiptVo.getPmds055(), "", 0);
//
//
//                for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
//                    //更新采购明细已填数量，已回填数量取反再新增就是减
//                    procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
//                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
//                    //删除回填记录
//                    procurementDetailsRecodeMapper.updateProcurementDetailsRecodeToDelete(procurementDetailsRecode);
//
//                }
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }

    /**
     * 采购收货送检单回调-通过来料检验,IncomingInspection
     */
    //@Transactional(rollbackFor = Exception.class)//测试代码逻辑才能开启事务，测试回调不能开始事务
//    @Scheduled(cron = "0/10 * * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 10000)//开启定时同步
//    //@Async(value = "taskExecutor")
    public void purchaseReceiptCallbackByIncomingInspection() {
        //查询没有回调的数据
//        List<PurchaseNotReceiptVo> purchaseNotReceiptCallback = wmsPurchaseMapper.getPurchaseNotReceiptCallbackIncomingInspection();
        PurchaseNotReceiptVo purchaseNotReceiptVo = wmsPurchaseMapper.getPurchaseNotReceiptCallbackIncomingInspection();
//        List<String> sbillnoList = purchaseNotReceiptCallback.stream().map(PurchaseNotReceiptVo::getPmds055).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(purchaseNotReceiptVo) || ObjectUtils.isEmpty(purchaseNotReceiptVo.getPmds055())) {
            //无正常单据需要处理时，将回填超时得单据再重传下(注意，超时得提示信息需要固定，不能修改)
            purchaseNotReceiptVo = wmsPurchaseMapper.getPurchaseNotReceiptCallbackIncomingInspectionWithTimeOut();
            if (ObjectUtils.isEmpty(purchaseNotReceiptVo) || ObjectUtils.isEmpty(purchaseNotReceiptVo.getPmds055())) {
                return;
            }
        }

        try {
            //根据没有回调的数据查询明细
            List<PurchaseNotReceiptListVo> purchaseNotReceiptListCallback = wmsPurchaseMapper.getPurchaseNotReceiptListCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), purchaseNotReceiptVo.getTc());

            Map<String, List<PurchaseNotReceiptListVo>> listMap = purchaseNotReceiptListCallback.stream().collect(Collectors.groupingBy(PurchaseNotReceiptListVo::getSlno));
            //根据采购收货明细获取是采购单号
            Set<String> purchaseOrderNos = purchaseNotReceiptListCallback.stream().map(PurchaseNotReceiptListVo::getPmdt001).collect(Collectors.toSet());
            //查询采购单采购详情
            if (CollUtil.isEmpty(purchaseOrderNos)) {
                log.info("未获取到采购单信息");

                if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {  //特采类型单据
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "未获取到采购单信息", 2);
                } else {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "未获取到采购单信息", 2);
                }
                return;
            }

            //每次都重新拉取下erp采购单，避免ERP修改了和本地不同步
            for (String purchaseOrderNo : purchaseOrderNos) {
                poMpsinfoMapper.syncProcurementDetailsByOrderNo(purchaseOrderNo);
            }

            //查询是否拉取erp采购单数据
            int checkProcurementDetails = wmsPurchaseMapper.checkProcurementDetails(purchaseOrderNos);
            if (checkProcurementDetails <= 0) {
                if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "未同步到ERP上的采购单据，请稍后重新尝试", 2);
                } else {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "未同步到ERP上的采购单据，请稍后重新尝试", 2);
                }
                return;
            }
            //获取ERP中可回填的物料数量信息 TODO zs 20240412 没考虑验退，出问题的时候再改，有数据可以验证
            List<ProcurementDetailsVo> procurementDetailsVos = wmsPurchaseMapper.getProcurementDetailsVo(purchaseOrderNos, 2);
            //没有数据时不会写
            String join = StringUtils.join(purchaseOrderNos, ",");
            if (CollUtil.isEmpty(procurementDetailsVos)) {
                String pmdt006 = purchaseNotReceiptListCallback.get(0).getPmdt006();
                //更新相应表状态为已下发
                if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "料号:" + pmdt006 + "对应采购采购单：" + join + "来料检验可回写数量不足，该单未回写!", 2);
                } else {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "料号:" + pmdt006 + "对应采购采购单：" + join + "来料检验可回写数量不足，该单未回写!", 2);
                }
                return;
            } else {
                for (PurchaseNotReceiptListVo purchaseNotReceiptListVo : purchaseNotReceiptListCallback) {
                    //比较待回填数量和可回填数量，校验合法性
                    BigDecimal reduce = procurementDetailsVos.stream().filter(item -> item.getPmdn001().equals(purchaseNotReceiptListVo.getPmdt006())).map(ProcurementDetailsVo::getPmdn007).reduce(BigDecimal.ZERO, BigDecimal::add);

                    // TODO zs 20240412 没考虑验退，出问题的时候再改，有数据可以验证
                    BigDecimal returnqty = procurementDetailsVos.stream().filter(item -> item.getPmdn001().equals(purchaseNotReceiptListVo.getPmdt006())).map(ProcurementDetailsVo::getReturnQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //验退数量
                    BigDecimal pmdt006 = procurementDetailsVos.stream().filter(item -> item.getPmdn001().equals(purchaseNotReceiptListVo.getPmdt006())).map(ProcurementDetailsVo::getPmdo016).reduce(BigDecimal.ZERO, BigDecimal::add);
                    reduce = reduce.add(pmdt006);
                    if (purchaseNotReceiptListVo.getPmdt020().compareTo(reduce.subtract(returnqty)) > 0) {
                        //更新相应表状态为已下发
                        if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                            wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "料号:" + purchaseNotReceiptListVo.getPmdt006() + "对应采购采购单：" + join + "来料检验可回写数量不足，该单未回写!", 2);
                        } else {
                            wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "料号:" + purchaseNotReceiptListVo.getPmdt006() + "对应采购采购单：" + join + "来料检验可回写数量不足，该单未回写!", 2);
                        }
                        return;
                    }
                }
            }
            //根据采购单分组
            Map<String, List<ProcurementDetailsVo>> procurementDetailsMap = procurementDetailsVos.stream().collect(Collectors.groupingBy(ProcurementDetailsVo::getPmdldocno));

            //遍历多个采购收货单
//        for (PurchaseNotReceiptVo purchaseNotReceiptVo : purchaseNotReceiptCallback) {
            purchaseNotReceiptVo.setActionType(Constant.ActionType_I);
            purchaseNotReceiptVo.setPmdssite(Constant.PMDSSITE_AMA);

            //获取当前这个采购收货单的详情数据
            List<PurchaseNotReceiptListVo> purchaseNotReceiptListVos = listMap.get(purchaseNotReceiptVo.getPmds055());
            //如果是特采则在单号后加tc
            if (purchaseNotReceiptVo.getTc() == 1) {
                purchaseNotReceiptVo.setPmds055(purchaseNotReceiptVo.getPmds055() + "-tc");
            }
            //保存回填记录
            List<ProcurementDetailsRecode> procurementDetailsRecodes = new ArrayList<>();
            //反填的采购单详情，带上项次
            List<PurchaseNotReceiptListReq> purchaseNotReceiptListReqs = new ArrayList<>();
            if (CollectionUtils.isEmpty(purchaseNotReceiptListVos)) {
                log.error("质检单质检合格明细为空");
                if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "质检单质检合格明细为空", 2);
                } else {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "质检单质检合格明细为空", 2);
                }
                throw new RuntimeException("质检单质检合格明细为空");
            }
            //遍历采购单收货明细，找到ERP 采购单明细对应的项次
            for (PurchaseNotReceiptListVo purchaseNotReceiptListVo : purchaseNotReceiptListVos) {
                //获取这个采购收货单详情对应采购单的采购详情
                List<ProcurementDetailsVo> procurementDetailsVos1 = procurementDetailsMap.get(purchaseNotReceiptListVo.getPmdt001());
                if (CollUtil.isEmpty(procurementDetailsVos1)) {
                    if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "未查询到ERP上对应采购订单的可回填物料信息，请核实！", 2);
                    } else {
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "未查询到ERP上对应采购订单的可回填物料信息，请核实！", 2);
                    }
                    continue;
                }
                //根据物料编号过滤出当前采购收货单的详情物料对应的采购单的采购物料明细，会有多个  TODO zs 20240412 没考虑验退，出问题的时候再改，有数据可以验证
                List<ProcurementDetailsVo> procurementDetailsVoList = procurementDetailsVos1.stream()
                        .filter(procurementDetailsVo -> procurementDetailsVo.getPmdn001().equals(purchaseNotReceiptListVo.getPmdt006())
                                && (procurementDetailsVo.getPmdn007().add(procurementDetailsVo.getPmdo016()).subtract(procurementDetailsVo.getReturnQty())).compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());

                //取出当前采购收货单的详情物料要回填的数量
                BigDecimal returnQty = new BigDecimal(purchaseNotReceiptListVo.getPmdt020().toString());
                //遍历对应的采购单的采购物料明细，给每个项次分配回填数量
                for (ProcurementDetailsVo procurementDetailsVo : procurementDetailsVoList) {
                    //如果有验退数量 则以下计算时 数量 = 数量加验退数量
                    if (ObjectUtil.isNotEmpty(procurementDetailsVo.getPmdo016()) && procurementDetailsVo.getPmdo016().compareTo(BigDecimal.ZERO) > 0) {
                        procurementDetailsVo.setPmdn007(procurementDetailsVo.getPmdn007().add(procurementDetailsVo.getPmdo016()));
                    }
                    log.info("procurementDetailsVo: {}", procurementDetailsVo);
                    //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
                    purchaseNotReceiptVo.setPmds011(procurementDetailsVo.getPmdl005());
                    //3401	生产性进货报检单; 3410	委外采购报检单 3402 德富采购单
//                    if (purchaseNotReceiptListVo.getPmdt001().contains("AMA-3399-")) {
//                        purchaseNotReceiptVo.setPmdsdocno("3402");
//                    } else {
//                        purchaseNotReceiptVo.setPmdsdocno(procurementDetailsVo.getPmdl005() == 1 ? Constant.PMDSDOCNO_3401 : Constant.PMDSDOCNO_3410);
//                    }
                    if (procurementDetailsVo.getPmdl005() == 1) {
                        purchaseNotReceiptVo.setPmdsdocno(Constant.PMDSDOCNO_3401);
                    } else if (procurementDetailsVo.getPmdl005() == 3) {
                        purchaseNotReceiptVo.setPmdsdocno(Constant.PMDSDOCNO_3402);
                    } else {
//                        if (procurementDetailsVo.getPmdldocno().contains("AMA-3399-")){
//                            purchaseNotReceiptVo.setPmdsdocno("3499");
//                        }
                        purchaseNotReceiptVo.setPmdsdocno(Constant.PMDSDOCNO_3410);
                    }
                    //直接创建要回调的采购收货明细详情，数量已以实际各个项次能回填的数量为准
                    PurchaseNotReceiptListReq bean = BeanUtil.toBean(purchaseNotReceiptListVo, PurchaseNotReceiptListReq.class);
                    //采购项次
                    bean.setPmdt002(procurementDetailsVo.getPmdnseq());
                    //采购项序
                    bean.setPmdt003(procurementDetailsVo.getPmdoseq1());
                    //采购分批序
                    bean.setPmdt004(String.valueOf(procurementDetailsVo.getPmdoseq2()));
                    if (procurementDetailsVo.getPmdl005() == 3) {
                        bean.setPmdt016("901");
                    }
                    //创建回填记录
                    ProcurementDetailsRecode procurementDetailsRecode = BeanUtil.toBean(procurementDetailsVo, ProcurementDetailsRecode.class);
                    //批号
                    procurementDetailsRecode.setBatchno(purchaseNotReceiptListVo.getPmdt018());
                    procurementDetailsRecode.setIsDelete(0);
                    //来源单号是采购收货单号
                    procurementDetailsRecode.setCheckno(purchaseNotReceiptVo.getPmds055());
                    //剩余可回填数量大于等于需要回填数量，该项次回填的是需要回填数量 TODO zs 20240412 没考虑验退，出问题的时候再改，有数据可以验证
                    if ((procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty())).compareTo(returnQty) >= 0) {
                        bean.setPmdt020(returnQty);
                        procurementDetailsRecode.setReturnQty(returnQty);
                        purchaseNotReceiptListReqs.add(bean);
                        procurementDetailsRecodes.add(procurementDetailsRecode);
                        //修改已回填数量加上需要回填数量
                        procurementDetailsVo.setReturnQty(procurementDetailsVo.getReturnQty().add(returnQty));
                        //需要回填数量已全部回填，退出循环
                        break;
                    } else {
                        //剩余可回填数量小于需要回填数量，该项次回填的是剩余可回填数量 TODO zs 20240412 没考虑验退，出问题的时候再改，有数据可以验证
                        bean.setPmdt020(procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty()));
                        procurementDetailsRecode.setReturnQty(procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty()));

                        //需要回填的数量 = 需要回填的数量 - 剩余可回填数量 TODO zs 20240412 没考虑验退，出问题的时候再改，有数据可以验证
                        returnQty = returnQty.subtract(procurementDetailsVo.getPmdn007().subtract(procurementDetailsVo.getReturnQty()));
                        purchaseNotReceiptListReqs.add(bean);
                        procurementDetailsRecodes.add(procurementDetailsRecode);
                        //修改已回填数量为该全部已回填
                        procurementDetailsVo.setReturnQty(procurementDetailsVo.getPmdn007());

                    }
                }
            }
            //-----------测试逻辑代码---------
//            Map<String, String> map =new HashMap<>();
//            map.put("pmdtdocno", "AMA-3401-" + System.currentTimeMillis());
//            XmlResp xmlResp = new XmlResp("0","",map);
//            if(xmlResp.getCode().equals("0")){
//                //更新相应表状态为已下发
//                wmsPurchaseMapper.updatePurchaseReceiptCallback(purchaseNotReceiptVo.getPmds055(),xmlResp.getData().get("pmdtdocno"), 1);
//                for (ProcurementDetailsRecodeVo procurementDetailsRecode : procurementDetailsRecodes) {
//                    procurementDetailsRecode.setReturnNo(xmlResp.getData().get("pmdtdocno"));
//                    //更新采购明细已填数量
//                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
//                    //保存记录
//                    procurementDetailsRecodeVoMapper.insert(procurementDetailsRecode);
//                }
//            }else {
//                //更新相应表状态为已下发
//                wmsPurchaseMapper.updatePurchaseReceiptCallback(purchaseNotReceiptVo.getPmds055(),null, 2);
//            }
            //-----------测试逻辑代码---------
            if (CollectionUtils.isEmpty(purchaseNotReceiptListReqs)) {
                log.info("采购入库来料检验明细为空");
                log.info("采购入库来料检验明细：{}", purchaseNotReceiptListVos);
                log.info("采购入库单明细：{}", procurementDetailsMap);
                log.info("soap接口来料检验回调失败->{}");
                //更新相应表状态为已下发
                if (purchaseNotReceiptVo.getPmds055().contains("tc")) {

                    String substringBefore = StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc");
                    //更新相应表状态为已下发
                    if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "采购单：" + join + "来料检验未回写!", 2);
                    } else {
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(substringBefore, "采购单：" + join + "来料检验未回写!", 2);
                    }
                } else {

                    //更新相应表状态为已下发
                    if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "采购单：" + join + "来料检验未回写!", 2);
                    } else {
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "采购单：" + join + "来料检验未回写!", 2);
                    }
                }
//            wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "采购单：" + purchaseNotReceiptVo.getPmdsdocno() + "来料检验未回写!", 2);
                return;
            }
            List<PurchaseNotReceiptListReq> collect = purchaseNotReceiptListReqs.stream().filter(item -> item.getPmdt020().compareTo(BigDecimal.ZERO) <= 0).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                log.info("采购入库来料检验检验合格数量有为0的数据，不回写erp");
                log.info("采购入库来料检验检验合格数量有为0的数据：数据集-->>{}", JSONObject.toJSONString(collect));

                if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "采购入库来料检验检验合格数量有为0的数据，不回写erp", 2);
                } else {
                    wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "采购入库来料检验检验合格数量有为0的数据，不回写erp", 2);
                }
                return;
            }
            String resMessage = soapXmlUtil.getSoapXml("PurchaseGet", "pmds_t", "pmdt_t", purchaseNotReceiptVo, purchaseNotReceiptListReqs);
            try {
//                log.info("采购收货送检请求报文->{}",resMessage);
                //转换为soap消息
                log.info("soap接口采购收货回调请求->{}", resMessage);
                //发送soap消息，并解析结果
                String result;
                try {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                } catch (Exception e) {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                }
                //返回结果处理
                if (purchaseNotReceiptListReqs.size() >= 50) {
                    Thread.sleep(120 * 1000);
                } else if (purchaseNotReceiptListReqs.size() >= 30) {
                    Thread.sleep(60 * 1000);
                } else if (purchaseNotReceiptListReqs.size() >= 10) {
                    Thread.sleep(30 * 1000);
                } else if (purchaseNotReceiptListReqs.size() >= 5) {
                    Thread.sleep(15 * 1000);
                }
                log.info("soap接口采购收货回调返回->{}", result);
                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                if (xmlResp.getCode().equals("0")) {
                    if (purchaseNotReceiptVo.getPmds055().contains("tc")) {
                        String substringBefore = StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc");
                        //更新相应表状态为已下发
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(substringBefore, xmlResp.getData().get("pmdsdocno"), 1);
                    } else {
                        //更新相应表状态为已下发
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), xmlResp.getData().get("pmdsdocno"), 1);
                    }

                    for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
                        procurementDetailsRecode.setReturnNo(xmlResp.getData().get("pmdsdocno"));
                        //更新采购明细已填数量
                        wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
                        //保存记录
                        procurementDetailsRecodeMapper.insert(procurementDetailsRecode);
                    }
                } else {
                    //更新相应表状态为已下发
                    if (purchaseNotReceiptVo.getPmds055().contains("tc")) {
                        String substringBefore = StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc");
                        //更新相应表状态为已下发
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(substringBefore, xmlResp.getMessage(), 2);
                    } else {
                        //更新相应表状态为已下发
                        wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), xmlResp.getMessage(), 2);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        }
        } catch (Exception e) {
            if (CollUtil.isNotEmpty(Collections.singleton(purchaseNotReceiptVo.getTc())) && purchaseNotReceiptVo.getTc() == 1) {
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(StringUtils.substringBefore(purchaseNotReceiptVo.getPmds055(), "-tc"), "非常见的数据处理问题，请联系开发人员处理", 2);
            } else {
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(purchaseNotReceiptVo.getPmds055(), "非常见的数据处理问题，请联系开发人员处理", 2);
            }
            e.printStackTrace();
        }
    }

    /**
     * 删除采购收货回调-通过来料检验,IncomingInspection
     */
    //@Transactional(rollbackFor = Exception.class) //测试代码逻辑才能开启事务，测试回调不能开始事务
    public String deletePurchaseReceiptCallbackIncomingInspection(String orderNo, boolean flg) {

        DeletePurchaseNotReceiptVo deletePurchaseNotReceiptVo = wmsPurchaseMapper.getDeletePurchaseReceiptCallbackIncomingInspection(orderNo);
        if (ObjectUtils.isEmpty(deletePurchaseNotReceiptVo) || StringUtils.isBlank(deletePurchaseNotReceiptVo.getPmdsdocno())) {
            log.info("单据：{}", deletePurchaseNotReceiptVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        //找到未删除回填记录
        LambdaQueryWrapper<ProcurementDetailsRecode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcurementDetailsRecode::getCheckno, orderNo)
                .eq(ProcurementDetailsRecode::getIsDelete, 0);
        List<ProcurementDetailsRecode> procurementDetailsRecodes = procurementDetailsRecodeMapper.selectList(queryWrapper);
        //----------测试逻辑代码---------
//        Map<String, String> map =new HashMap<>();
//        map.put("pmdtdocno", "AMA-3401-" + System.currentTimeMillis());
//        XmlResp xmlResp = new XmlResp("0","",map);
//        if(xmlResp.getCode().equals("0")){
//            //更新相应表状态为未下发
//            wmsPurchaseMapper.updatePurchaseReceiptCallback(deletePurchaseNotReceiptVo.getPmds055(), "", 0);
//
//            //找到未删除回填记录
//            LambdaQueryWrapper<ProcurementDetailsRecodeVo> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(ProcurementDetailsRecodeVo::getPmdl008, orderNo)
//                    .eq(ProcurementDetailsRecodeVo::getIsDelete, 0);
//            List<ProcurementDetailsRecodeVo> procurementDetailsRecodeVos = procurementDetailsRecodeVoMapper.selectList(queryWrapper);
//            for (ProcurementDetailsRecodeVo procurementDetailsRecode : procurementDetailsRecodeVos) {
//                //更新采购明细已填数量，已回填数量取反再新增就是减
//                procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
//                wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
//                //删除回填记录
//                procurementDetailsRecodeVoMapper.updateToDelete(procurementDetailsRecode);
//
//            }
//        }
        //----------测试逻辑代码---------
        deletePurchaseNotReceiptVo.setActionType(Constant.ActionType_D);
        ProcurementDetailsRecode procurementDetailsRecodeVo = procurementDetailsRecodes.get(0);
        //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
        deletePurchaseNotReceiptVo.setPmds011(procurementDetailsRecodeVo.getPmdl005());
        String resMessage = soapXmlUtil.getSoapXml("PurchaseGet", "pmds_t", deletePurchaseNotReceiptVo);
        try {
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库送检单单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                if (flg) {
                    wmsPurchaseMapper.updaCheckZjFlg(deletePurchaseNotReceiptVo.getPmds055());
                    //反审出库单
                    wmsPurchaseMapper.updateInstoreByCheckNo(deletePurchaseNotReceiptVo.getPmds055(), "0");
                    //删除出库单
                    wmsPurchaseMapper.deleteInstoreByCheckNo(deletePurchaseNotReceiptVo.getPmds055(), "0");
                }
                //更新相应表状态为未下发
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(deletePurchaseNotReceiptVo.getPmds055(), xmlResp.getMessage(), 0);
                for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
                    //更新采购明细已填数量，已回填数量取反再新增就是减
                    procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
                    //删除回填记录
                    procurementDetailsRecodeMapper.updateProcurementDetailsRecodeToDelete(procurementDetailsRecode);
                }
            }
            return xmlResp.getMessage();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return "系统异常";
    }

    /**
     * 删除采购收货回调-通过来料检验,IncomingInspection
     */
    //@Transactional(rollbackFor = Exception.class) //测试代码逻辑才能开启事务，测试回调不能开始事务
    public String checkmaterialRollback() {
        String orderNo = wmsPurchaseMapper.getCheckmaterialRollback();
        if (ObjectUtil.isEmpty(orderNo)) {
            return "未查询到要反写反写数据";
        }
        boolean flg = true;
        DeletePurchaseNotReceiptVo deletePurchaseNotReceiptVo = wmsPurchaseMapper.getDeletePurchaseReceiptCallbackIncomingInspection(orderNo);
        if (ObjectUtils.isEmpty(deletePurchaseNotReceiptVo) || StringUtils.isBlank(deletePurchaseNotReceiptVo.getPmdsdocno())) {
            log.info("单据：{}", deletePurchaseNotReceiptVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        //找到未删除回填记录
        LambdaQueryWrapper<ProcurementDetailsRecode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcurementDetailsRecode::getCheckno, orderNo)
                .eq(ProcurementDetailsRecode::getIsDelete, 0);
        List<ProcurementDetailsRecode> procurementDetailsRecodes = procurementDetailsRecodeMapper.selectList(queryWrapper);
        //----------测试逻辑代码---------
        //----------测试逻辑代码---------
        deletePurchaseNotReceiptVo.setActionType(Constant.ActionType_D);
        ProcurementDetailsRecode procurementDetailsRecodeVo = procurementDetailsRecodes.get(0);
        //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
        deletePurchaseNotReceiptVo.setPmds011(procurementDetailsRecodeVo.getPmdl005());
        String resMessage = soapXmlUtil.getSoapXml("PurchaseGet", "pmds_t", deletePurchaseNotReceiptVo);
        try {
            //转换为soap消息
            log.info(resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库送检单单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                if (flg) {
                    wmsPurchaseMapper.updaCheckZjFlg(deletePurchaseNotReceiptVo.getPmds055());
                    //反审出库单
                    wmsPurchaseMapper.updateInstoreByCheckNo(deletePurchaseNotReceiptVo.getPmds055(), "0");
                    //删除出库单
                    wmsPurchaseMapper.deleteInstoreByCheckNo(deletePurchaseNotReceiptVo.getPmds055(), "0");
                }
                //更新相应表状态为未下发
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(deletePurchaseNotReceiptVo.getPmds055(), xmlResp.getMessage(), 0);


                for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
                    //更新采购明细已填数量，已回填数量取反再新增就是减
                    procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
                    //删除回填记录
                    procurementDetailsRecodeMapper.updateProcurementDetailsRecodeToDelete(procurementDetailsRecode);

                }
                //更新表数据
                wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 1, xmlResp.getMessage());
            } else {
                //更新表数据
                wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, xmlResp.getMessage());
            }
            return xmlResp.getMessage();
        } catch (Exception e) {
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "系统回写异常，请联系开发人员处理");
            e.printStackTrace();
        }
        return "系统异常";
    }

//    /**
//     * 采购入库单回填-采购入库
//     */
//    public void purchaseReceiptFormCallback() {
//        //查询没有回调的数据
//        List<PurchaseReceiptFormVo> receiptFormVos = wmsPurchaseMapper.getPurchaseReceiptFormCallback();
//
//        List<String> sbillnoList = receiptFormVos.stream().map(PurchaseReceiptFormVo::getPmds055).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(sbillnoList)) {
//            return;
//        }
//        //根据没有回调的数据查询明细
//        List<PurchaseReceiptFormListVo> purchaseReceiptFormListVos = wmsPurchaseMapper.getPurchaseReceiptFormListCallback(sbillnoList);
//        Map<String, List<PurchaseReceiptFormListVo>> listMap = purchaseReceiptFormListVos.stream().collect(Collectors.groupingBy(PurchaseReceiptFormListVo::getInno));
////        //根据采购入库单对应ERP的收货单查找收货明细
////        Set<String> purchaseReceiptOrderNos = receiptFormVos.stream().map(PurchaseReceiptFormVo::getPmds006).collect(Collectors.toSet());
//        //根据采购单找对应ERP的收货单查找收货明细
//        Set<String> purchaseReceiptOrderNos = purchaseReceiptFormListVos.stream().map(PurchaseReceiptFormListVo::getPoSbillno).collect(Collectors.toSet());
//
//        //查询采购入库单采购详情
//        List<PurchaseReceiptDetailsVo> procurementDetailsVos = wmsPurchaseMapper.getPurchaseReceiptDetailsVo(purchaseReceiptOrderNos);
//        //根据采购入库单分组
//        Map<String, List<PurchaseReceiptDetailsVo>> procurementReceiptDetailsMap = procurementDetailsVos.stream().collect(Collectors.groupingBy(PurchaseReceiptDetailsVo::getPmdsdocno));
//
//        for (PurchaseReceiptFormVo purchaseReceiptFormVo : receiptFormVos) {
//            purchaseReceiptFormVo.setActionType(Constant.ActionType_I);
//            purchaseReceiptFormVo.setPmdsdocno(Constant.PMDSDOCNO_3501);
//            purchaseReceiptFormVo.setPmdssite(Constant.PMDSSITE_AMA);
//
//            //保存回填记录
//            List<PurchaseReceiptDetailsRecode> purchaseReceiptDetailsRecodes = new ArrayList<>();
//            //反填的采购单详情，带上项次
//            List<PurchaseReceiptFormListReq> purchaseReceiptFormListReqs = new ArrayList<>();
//
//            //获取当前这个入库单的详情数据
//            List<PurchaseReceiptFormListVo> purchaseReceiptFormListVos1 = listMap.get(purchaseReceiptFormVo.getPmds055());
//
//            for (PurchaseReceiptFormListVo receiptFormListVo : purchaseReceiptFormListVos1) {
//
//                //获取这个采购入库单详情对应收货单的详情
//                List<PurchaseReceiptDetailsVo> receiptDetailsVos = procurementReceiptDetailsMap.get(receiptFormListVo.getPoSbillno());
//
//                //根据物料编号过滤出当前采购收货单的详情物料对应的采购单的采购物料明细，会有多个
//                List<PurchaseReceiptDetailsVo> procurementDetailsVoList = receiptDetailsVos.stream()
//                        .filter(receiptDetailsVo -> receiptDetailsVo.getPmdt006().equals(receiptFormListVo.getPmdt006())
//                                && (receiptDetailsVo.getPmdt053().subtract(receiptDetailsVo.getPmdt054()).subtract(receiptDetailsVo.getPmdt055())
//                                .subtract(receiptDetailsVo.getReturnQty())).compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
//
//                //取出当前采购收货单的详情物料要回填的数量
//                BigDecimal returnQty = new BigDecimal(receiptFormListVo.getPmdt020().toString());
//                if(CollectionUtils.isEmpty(procurementDetailsVoList)){
//                    log.info("回填明细：{}", receiptFormListVo);
//                    log.info("收货单明细：{}", procurementDetailsVoList);
//                    throw new RuntimeException("ERP对应单据已允收数量<= 已回填数量");
//                }
//                //遍历对应的采购单的采购物料明细，给每个项次分配回填数量
//                for (PurchaseReceiptDetailsVo purchaseReceiptDetailsVo : procurementDetailsVoList) {
//
//                    //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
//                    purchaseReceiptFormVo.setPmds011(purchaseReceiptDetailsVo.getPmds011());
//                    //3401	生产性进货报检单; 3410	委外采购报检单
//                    purchaseReceiptFormVo.setPmdsdocno(purchaseReceiptDetailsVo.getPmds011() == 1 ? Constant.PMDSDOCNO_3501: Constant.PMDSDOCNO_3510);
//                    //直接创建要回调的采购收货明细详情，数量已以实际各个项次能回填的数量为准
//                    PurchaseReceiptFormListReq bean = BeanUtil.toBean(receiptFormListVo, PurchaseReceiptFormListReq.class);
//                    //采购项次
//                    bean.setPmdt028(purchaseReceiptDetailsVo.getPmdtseq());
//                    //创建回填记录
//                    PurchaseReceiptDetailsRecode purchaseReceiptDetailsRecode = BeanUtil.toBean(purchaseReceiptDetailsVo, PurchaseReceiptDetailsRecode.class);
//                    //批号
//                    purchaseReceiptDetailsRecode.setBatchno(receiptFormListVo.getPmdt018());
//                    purchaseReceiptDetailsRecode.setIsDelete(0);
//                    //采购入库单号是采购入库单号
//                    purchaseReceiptDetailsRecode.setPurchaseReceipt(purchaseReceiptFormVo.getPmds055());
//                    //收货单号,需要考虑跨收货单情况
//                    //purchaseReceiptFormVo.setPmds006(purchaseReceiptDetailsVo.getPmdsdocno());
//                    bean.setPmdsdocno(purchaseReceiptDetailsVo.getPmdsdocno());
//                    //剩余可回填数量大于等于需要回填数量，该项次回填的是需要回填数量
//                    if((purchaseReceiptDetailsVo.getPmdt053().subtract(purchaseReceiptDetailsVo.getPmdt054()).subtract(purchaseReceiptDetailsVo.getPmdt055())
//                            .subtract(purchaseReceiptDetailsVo.getReturnQty()))
//                            .compareTo(returnQty) >= 0){
//                        bean.setPmdt020(returnQty);
//                        purchaseReceiptDetailsRecode.setReturnQty(returnQty);
//                        purchaseReceiptFormListReqs.add(bean);
//                        purchaseReceiptDetailsRecodes.add(purchaseReceiptDetailsRecode);
//                        //修改已回填数量加上需要回填数量
//                        purchaseReceiptDetailsVo.setReturnQty(purchaseReceiptDetailsVo.getReturnQty().add(returnQty));
//                        //需要回填数量已全部回填，退出循环
//                        break;
//                    }else {
//                        //剩余可回填数量小于需要回填数量，该项次回填的是剩余可回填数量
//                        bean.setPmdt020(purchaseReceiptDetailsVo.getPmdt020().subtract(purchaseReceiptDetailsVo.getReturnQty()));
//                        purchaseReceiptDetailsRecode.setReturnQty(purchaseReceiptDetailsVo.getPmdt053().subtract(purchaseReceiptDetailsVo.getPmdt054()).subtract(purchaseReceiptDetailsVo.getPmdt055())
//                                .subtract(purchaseReceiptDetailsVo.getReturnQty()));
//
//                        //需要回填的数量 = 需要回填的数量 - 剩余可回填数量
//                        returnQty = returnQty.subtract(purchaseReceiptDetailsVo.getPmdt053().subtract(purchaseReceiptDetailsVo.getPmdt054()).subtract(purchaseReceiptDetailsVo.getPmdt055())
//                                .subtract(purchaseReceiptDetailsVo.getReturnQty()));
//                        purchaseReceiptFormListReqs.add(bean);
//                        purchaseReceiptDetailsRecodes.add(purchaseReceiptDetailsRecode);
//                        //修改已回填数量为该全部已回填
//                        purchaseReceiptDetailsVo.setReturnQty(purchaseReceiptDetailsVo.getPmdt020());
//                    }
//                }
//
//            }
//
//            //考虑会有跨收货单修改根据收货单分开回调,//收货单号,需要考虑跨收货单情况
//            Map<String, List<PurchaseReceiptFormListReq>> pmdsdocnoMap = purchaseReceiptFormListReqs.stream().collect(Collectors.groupingBy(PurchaseReceiptFormListReq::getPmdsdocno));
//            Set<String> pmdsdocnos = purchaseReceiptFormListReqs.stream().map(PurchaseReceiptFormListReq::getPmdsdocno).collect(Collectors.toSet());
//            for (String pmdsdocno : pmdsdocnos) {
//                purchaseReceiptFormVo.setPmdsdocno(pmdsdocno);
//                List<PurchaseReceiptFormListReq2> purchaseReceiptFormListReq2s = BeanUtil.copyToList(pmdsdocnoMap.get(pmdsdocno), PurchaseReceiptFormListReq2.class);
//                String resMessage = soapXmlUtil.getSoapXml("PurchaseIn","pmds_t","pmdt_t", purchaseReceiptFormVo, purchaseReceiptFormListReq2s);
////                try {
////                    //转换为soap消息
////                    MessageFactory msgFactory = MessageFactory.newInstance();
////                    SOAPMessage message = msgFactory.createMessage();
////                    SOAPPart soapPart = message.getSOAPPart();
////                    byte[] buffer = resMessage.getBytes();
////                    ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
////                    StreamSource source = new StreamSource(stream);
////                    soapPart.setContent(source);
////                    message.writeTo(System.out);
    //log.info(resMessage);
////                    //log.info("采购入库单回调：{}",resMessage);
////                    //发送soap消息，并解析结果
////                    String result = soapXmlUtil.sendSoapMessage(message);
////                    log.info("采购入库单回调结果: {}",result);
////                    XmlResp xmlResp = soapXmlUtil.analysisXml(result);
////                    if(xmlResp.getCode().equals("0")){
////                        //更新相应表状态为已下发
////                        wmsPurchaseMapper.updatePurchaseReceiptFormCallback(purchaseReceiptFormVo.getPmds055(), xmlResp.getData().get("pmdsdocno"), 1,9);
////                        for (PurchaseReceiptDetailsRecode purchaseReceiptDetailsRecode : purchaseReceiptDetailsRecodes) {
////                            purchaseReceiptDetailsRecode.setReturnNo(xmlResp.getData().get("pmdsdocno"));
////                            //更新采购明细已填数量
////                            wmsPurchaseMapper.updateAddPurchaseReceipt(purchaseReceiptDetailsRecode);
////                            //保存记录
////                            purchaseReceiptDetailsRecodeMapper.insert(purchaseReceiptDetailsRecode);
////                        }
////                    }else {
////                        wmsPurchaseMapper.updatePurchaseReceiptFormCallback(purchaseReceiptFormVo.getPmds055(), xmlResp.getMessage(), 2,2);
////                    }
////                }catch (Exception e){
////                    e.printStackTrace();
////                }
//            }
//
//        }
//    }


    /**
     * 采购入库货架位绑定回填-采购入库RackBinding
     */
//    @Scheduled(cron = "0/7 * * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 11000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void purchaseReceiptFormCallbackByRackBinding() {
        //查询没有回调的数据， 2024.04.10 zs 缺陷：由于取的调拨单中的第一条可回填数据，如果失败，置整个调拨单回填失败，该调拨单后面未回填的不会再进行回填
        //2024.04.10 zs 本次取到的数据不考虑检验单号，可能该检验单号已经被回填了，下面的逻辑重新取
        List<PurchaseReceiptRackBinding> rackBindings = wmsPurchaseMapper.getPurchaseReceiptFormCallbackByRackBinding();

        if (ObjectUtils.isEmpty(rackBindings)) {
            //TODO 常规调拨处理完，再自动尝试回填失败单据下还未回填的数据

            return;
        }

        //捕获异常，设置单据状态为失败，避免总是取到该单据导致后续任务无法处理
        try {
            //获取单据的全部物料详情
            // 2024.04.10 按照目前sql一条调拨明细可能会对应多个质检单，那么该列表中调拨明细记录就会重复，所以一次只能取一条需求+待抵扣的质检单进行回填，所以废弃该方案
//            List<PurchaseReceiptRackBinding> rackBindings = wmsPurchaseMapper.getPurchaseReceiptFormCallbackByRackBindingWithMoveno(rackBindings_pre.get(0).getMoveno());

//            Set<String> inspectionNos = rackBindings.stream().map(PurchaseReceiptRackBinding::getInspectionNo).collect(Collectors.toSet());
            //根据所要回填的调拨单号重新获取对应物料明细关联的ERP上的报检单号（包括已经被回填的，无法排除）
            List<String> inspectionNosInErp = wmsPurchaseMapper.getInspectionNosByStMoveMaterial(
                    rackBindings.get(0).getMoveno(),
                    rackBindings.get(0).getMcode(),
                    rackBindings.get(0).getBatchno(),
                    rackBindings.get(0).getSourceStorage());

            //拉取最新的质检单对应ERP中的单据详情(拉取的为还可已回填的单据，已回填完成的不会获取)
            for (String inspection : inspectionNosInErp) {
                wmsPurchaseMapper.getCheckDetailFromErpByCheckNo(inspection);
            }

            //根据反填的送检单找到对应明细
            List<PurchaseReceiptDetailsVo> procurementDetailsVos = wmsPurchaseMapper.getPurchaseReceiptDetailsVoByInspectionNos(inspectionNosInErp);
            if (CollUtil.isEmpty(procurementDetailsVos)) {
                wmsPurchaseMapper.updateStMoveFillbackStatus(rackBindings.get(0).getMoveno(), "收货送检单暂未同步或对应送检单已收满，无法调拨", 2);
                return;
            }

            //根据ERP上的报检单分组
            Map<String, List<PurchaseReceiptDetailsVo>> procurementReceiptDetailsMap = procurementDetailsVos.stream().collect(Collectors.groupingBy(PurchaseReceiptDetailsVo::getPmdsdocno));

            //为了复用以前业务处理，所以每次只取一条检验单作为回填抵扣数据依据
            String dealInspectionNo = procurementDetailsVos.get(0).getPmdsdocno();
            for (PurchaseReceiptRackBinding rackBinding : rackBindings) {
                PurchaseReceiptFormVo purchaseReceiptFormVo = new PurchaseReceiptFormVo();
                purchaseReceiptFormVo.setActionType(Constant.ActionType_I);
                purchaseReceiptFormVo.setPmdsdocno(Constant.PMDSDOCNO_3501);
                purchaseReceiptFormVo.setPmdssite(Constant.PMDSSITE_AMA);
                purchaseReceiptFormVo.setPmdsdocdt(rackBinding.getDdate());
                purchaseReceiptFormVo.setPmds006(dealInspectionNo);
                purchaseReceiptFormVo.setPmds002(rackBinding.getMkerid());
                purchaseReceiptFormVo.setPmds054(Constant.PMDSSITE_WMS);
                purchaseReceiptFormVo.setPmds055(rackBinding.getMoveno() + '-' + rackBinding.getAutoid() + '-' + System.currentTimeMillis());
                List<PurchaseReceiptDetailsVo> receiptDetailsVos = procurementReceiptDetailsMap.get(dealInspectionNo);
                if (CollectionUtils.isEmpty(receiptDetailsVos)) {
                    log.error("收货送检单暂未同步: {}", dealInspectionNo);
                    wmsPurchaseMapper.updateStMoveFillbackStatus(rackBindings.get(0).getMoveno(), "收货送检单暂未同步或对应送检单已收满，无法调拨", 2);
                    return;
                }
                //不需要减去returnQty,这个数量会加到已入库数量
                List<PurchaseReceiptDetailsVo> procurementDetailsVoList = receiptDetailsVos.stream()
                        .filter(receiptDetailsVo -> receiptDetailsVo.getPmdt006().equals(rackBinding.getMcode())
                                && (receiptDetailsVo.getPmdt053().subtract(receiptDetailsVo.getPmdt054()).subtract(receiptDetailsVo.getPmdt055())).compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());

                //取出当前采购收货单的详情物料要回填的数量
                BigDecimal needReturnQty = rackBinding.getQty().subtract(rackBinding.getReturnQty());
                if (CollectionUtils.isEmpty(procurementDetailsVoList)) {
                    log.info("回填明细：{}", rackBinding);
                    log.info("收货单明细：{}", procurementDetailsVoList);

                    wmsPurchaseMapper.updateStMoveFillbackStatus(rackBindings.get(0).getMoveno(), "ERP对应单据已允收数量<= 已回填数量", 2);
                    return;
                }
                List<PurchaseReceiptFormListReq2> purchaseReceiptFormListReq2s = new ArrayList<>();
                //保存回填记录
                List<PurchaseReceiptDetailsRecode> purchaseReceiptDetailsRecodes = new ArrayList<>();
                //遍历对应的采购单的采购物料明细，给每个项次分配回填数量
                for (PurchaseReceiptDetailsVo purchaseReceiptDetailsVo : procurementDetailsVoList) {

                    //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
                    purchaseReceiptFormVo.setPmds011(purchaseReceiptDetailsVo.getPmds011());
                    //3401	生产性进货报检单; 3410	委外采购报检单
                    purchaseReceiptFormVo.setPmdsdocno(purchaseReceiptDetailsVo.getPmds011() == 1 ? Constant.PMDSDOCNO_3501 : Constant.PMDSDOCNO_3510);
                    //直接创建要回调的采购收货明细详情，数量已以实际各个项次能回填的数量为准
                    PurchaseReceiptFormListReq2 bean = new PurchaseReceiptFormListReq2();
                    //采购项次
                    bean.setPmdt028(purchaseReceiptDetailsVo.getPmdtseq());
                    bean.setPmdt006(rackBinding.getMcode());
                    bean.setPmdt016(rackBinding.getWarehouseLocation());
                    bean.setPmdt017(rackBinding.getStorage());
                    bean.setPmdt018(rackBinding.getBatchno());
                    bean.setPmdt063("");
                    bean.setPmdt059("ERP回调测试用例");
                    //创建回填记录
                    PurchaseReceiptDetailsRecode purchaseReceiptDetailsRecode = BeanUtil.toBean(purchaseReceiptDetailsVo, PurchaseReceiptDetailsRecode.class);
                    //批号
                    purchaseReceiptDetailsRecode.setBatchno(rackBinding.getBatchno());
                    purchaseReceiptDetailsRecode.setIsDelete(0);
                    purchaseReceiptDetailsRecode.setMoveNo(rackBinding.getMoveno());
                    purchaseReceiptDetailsRecode.setPurchaseReceipt(rackBinding.getInno());
                    purchaseReceiptDetailsRecode.setAutoid(rackBinding.getAutoid());

                    //计算本条质检单的剩余可回填数量
                    BigDecimal canFillBackByCurrentCheckNo = purchaseReceiptDetailsVo.getPmdt053()
                            .subtract(purchaseReceiptDetailsVo.getPmdt054())
                            .subtract(purchaseReceiptDetailsVo.getPmdt055());

                    //剩余可回填数量大于等于需要回填数量，该项次回填的是需要回填数量
                    if (canFillBackByCurrentCheckNo.compareTo(needReturnQty) >= 0) {
                        //如果上架数量大于 收货回填数量 则取上架数量
//                    if(returnQty.compareTo(rackBinding.getQty().subtract(rackBinding.getReturnQty())) > 0){
//                        returnQty = returnQty.subtract(rackBinding.getQty().subtract(rackBinding.getReturnQty()));
//                    }
//                        if(returnQty.compareTo(rackBinding.getReturnQty()) > 0){
//                            returnQty = returnQty.subtract(rackBinding.getReturnQty());
//                        }
                        bean.setPmdt020(needReturnQty);
                        purchaseReceiptDetailsRecode.setReturnQty(needReturnQty);
                        purchaseReceiptFormListReq2s.add(bean);
                        purchaseReceiptDetailsRecodes.add(purchaseReceiptDetailsRecode);
                        //修改已回填数量加上需要回填数量
                        purchaseReceiptDetailsVo.setReturnQty(purchaseReceiptDetailsVo.getPmdt054().add(needReturnQty));
                        //修改已入库数量加上需要回填数量
                        purchaseReceiptDetailsVo.setPmdt054(purchaseReceiptDetailsVo.getPmdt054().add(needReturnQty));
                        //需要回填数量已全部回填，退出循环
                        break;
                    } else {
                        //剩余可回填数量小于需要回填数量，该项次回填的是剩余可回填数量
                        bean.setPmdt020(canFillBackByCurrentCheckNo);
                        purchaseReceiptDetailsRecode.setReturnQty(canFillBackByCurrentCheckNo);

                        //需要回填的数量 = 需要回填的数量 - 剩余可回填数量
                        needReturnQty = needReturnQty.subtract(canFillBackByCurrentCheckNo);
                        purchaseReceiptFormListReq2s.add(bean);
                        purchaseReceiptDetailsRecodes.add(purchaseReceiptDetailsRecode);
                        //修改已回填数量为该全部已回填
                        purchaseReceiptDetailsVo.setReturnQty(purchaseReceiptDetailsVo.getPmdt020());
                        purchaseReceiptDetailsVo.setPmdt054(purchaseReceiptDetailsVo.getPmdt020());
                    }
                }
                if (CollectionUtils.isEmpty(purchaseReceiptFormListReq2s)) {

                }
                String resMessage = soapXmlUtil.getSoapXml("PurchaseIn", "pmds_t", "pmdt_t", purchaseReceiptFormVo, purchaseReceiptFormListReq2s);
                try {
                    //转换为soap消息
                    log.info(resMessage);
                    //log.info("采购入库单回调：{}",resMessage);
                    //发送soap消息，并解析结果
                    String result;
                    try {
                        result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                    } catch (Exception e) {
                        result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                    }

                    log.info("采购入库单回调结果: {}", result);
                    XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                    if (xmlResp.getCode().equals("0")) {
                        //清空主表状态为空，避免上一个状态为过账失败
                        wmsPurchaseMapper.updateStMoveFillbackStatusToNull(rackBindings.get(0).getMoveno());

                        for (PurchaseReceiptDetailsRecode purchaseReceiptDetailsRecode : purchaseReceiptDetailsRecodes) {
                            wmsPurchaseMapper.updatePurchaseReceiptFormCallbackRackBinding(purchaseReceiptDetailsRecode);
                            purchaseReceiptDetailsRecode.setReturnNo(xmlResp.getData().get("pmdsdocno"));
                            //更新采购明细已填数量 zs 20240409已修改为及时获取
//                            wmsPurchaseMapper.updateAddPurchaseReceipt(purchaseReceiptDetailsRecode);
                            //保存记录
                            purchaseReceiptDetailsRecodeMapper.insert(purchaseReceiptDetailsRecode);
                        }
                        //更新wsm及仓库上上架入库数量
                        wmsPurchaseNewMapper.wmsSrmUpStockqty(rackBinding.getMoveno());
                    } else {
                        //更新相应主表状态为回填失败
                        wmsPurchaseMapper.updateStMoveFillbackStatus(rackBindings.get(0).getMoveno(), xmlResp.getMessage(), 2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateStMoveFillbackStatus(rackBindings.get(0).getMoveno(), "非常见的数据处理问题，请联系开发人员处理", 2);
        }
    }

    /**
     * 采购入库单回调后自动过账不能删除
     * 删除采购入库单回调，
     */
    public void deletePurchaseReceiptFormCallback(DeletePurchaseReceiptFormCallbackReq req) {
//        DeletePurchaseReceiptFormVo deletePurchaseReceiptFormCallback = wmsPurchaseMapper.getDeletePurchaseReceiptFormCallback(orderNo);
//        if(ObjectUtils.isEmpty(deletePurchaseReceiptFormCallback) || StringUtils.isBlank(deletePurchaseReceiptFormCallback.getPmdsdocno())){
//            log.info("采购入库单单据：{}", deletePurchaseReceiptFormCallback);
//            throw new RuntimeException("采购入库单单据不存在或未反写ERP");
//        }
        //找到未删除回填记录
//        LambdaQueryWrapper<PurchaseReceiptDetailsRecode> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(PurchaseReceiptDetailsRecode::getPurchaseReceipt, orderNo)
//                .eq(PurchaseReceiptDetailsRecode::getIsDelete, 0);
//        List<PurchaseReceiptDetailsRecode> purchaseReceiptDetailsRecodes = purchaseReceiptDetailsRecodeMapper.selectList(queryWrapper);


        //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
//        deletePurchaseReceiptFormCallback.setPmds011(purchaseReceiptDetailsRecode.getPmds011());
        DeletePurchaseReceiptFormVo deletePurchaseReceiptFormCallback = BeanUtil.copyProperties(req, DeletePurchaseReceiptFormVo.class);
        deletePurchaseReceiptFormCallback.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("PurchaseIn", "pmds_t", deletePurchaseReceiptFormCallback);
        try {
            //转换为soap消息
            log.info(resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为未下发
//                wmsPurchaseMapper.updatePurchaseReceiptFormCallback(deletePurchaseReceiptFormCallback.getPmds055(), xmlResp.getData().get("pmdtdocno"), 1);
//
//                for (PurchaseReceiptDetailsRecode purchaseReceiptDetailsRecode1 : purchaseReceiptDetailsRecodes) {
//                    //更新采购明细已填数量，已回填数量取反再新增就是减
//                    purchaseReceiptDetailsRecode1.setReturnQty(purchaseReceiptDetailsRecode1.getReturnQty().negate());
//
//                    wmsPurchaseMapper.updateAddPurchaseReceipt(purchaseReceiptDetailsRecode1);
//                    //删除回填记录
//                    purchaseReceiptDetailsRecodeMapper.updatePurchaseReceiptDetailsRecodeToDelete(purchaseReceiptDetailsRecode1);
//
//                }
                log.info("成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 采购退货单回调
     */
    public void purchaseBackCallback() {
        //查询没有回调的数据
        List<PurchaseBackVo> purchaseBackVos = wmsPurchaseMapper.getPurchaseBackCallback();

        List<String> sbillnoList = purchaseBackVos.stream().map(PurchaseBackVo::getPmds055).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(sbillnoList)) {
            return;
        }
        //根据没有回调的数据查询明细
        List<PurchaseBackListVo> purchaseReceiptFormListVos = wmsPurchaseMapper.getPurchaseBackListCallback(sbillnoList);
        Map<String, List<PurchaseBackListVo>> listMap = purchaseReceiptFormListVos.stream().collect(Collectors.groupingBy(PurchaseBackListVo::getOutno));
        for (PurchaseBackVo purchaseBackVo : purchaseBackVos) {
            purchaseBackVo.setActionType(Constant.ActionType_I);
            purchaseBackVo.setPmdsdocno(Constant.PMDSDOCNO_3701);
            purchaseBackVo.setPmdssite(Constant.PMDSSITE_AMA);
            List<PurchaseBackListVo> purchaseReceiptFormListVos1 = listMap.get(purchaseBackVo.getPmds055());
            List<PurchaseBackListReq> purchaseReceiptFormListReqs = BeanUtil.copyToList(purchaseReceiptFormListVos1, PurchaseBackListReq.class);
            String resMessage = soapXmlUtil.getSoapXml("PurchaseBack", "pmds_t", "pmdt_t", purchaseBackVo, purchaseReceiptFormListReqs);
            try {
                //转换为soap消息
                MessageFactory msgFactory = MessageFactory.newInstance();
                SOAPMessage message = msgFactory.createMessage();
                SOAPPart soapPart = message.getSOAPPart();
                byte[] buffer = resMessage.getBytes();
                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
                StreamSource source = new StreamSource(stream);
                soapPart.setContent(source);
                message.writeTo(System.out);
                log.info(resMessage);
                //log.info("采购入库单回调：{}",resMessage);
                //发送soap消息，并解析结果
                String result;
                try {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                } catch (Exception e) {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                }
                log.info("采购入库单回调结果: {}", result);
                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                if (xmlResp.getCode().equals("0")) {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updatePurchaseBackCallback(purchaseBackVo.getPmds055(), xmlResp.getData().get("pmdtdocno"), 1);
                } else {
                    wmsPurchaseMapper.updatePurchaseBackCallback(purchaseBackVo.getPmds055(), xmlResp.getMessage(), 2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 仓间调拨单回调
     */
//    @Scheduled(cron = "20 0/1 * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 30000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void warehouseTransferCallback() {
        //查询没有回调的数据
        WarehouseTransferVo warehouseTransferVo = wmsPurchaseMapper.getWarehouseTransferCallback();
        log.info("warehouseTransferVos:{}", warehouseTransferVo);
//        List<String> sbillnoList = warehouseTransferVos.stream().map(WarehouseTransferVo::getIndc003).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(warehouseTransferVo)) {
            log.info("未查询到仓间调拨单回调数据，修改回写失败数据重新进行回写");
            wmsPurchaseMapper.warehouseTransferCallbackLose();
            return;
        }
        //根据没有回调的数据查询明细
        List<WarehouseTransferListVo> transferListVos = wmsPurchaseMapper.getWarehouseTransferListCallback(warehouseTransferVo.getIndc003());
        if (CollUtil.isEmpty(transferListVos)) {
            //发送soap消息，并解析结果
            wmsPurchaseMapper.updateWarehouseTransferCallback(warehouseTransferVo.getIndc003(), "没有明细资料,请确认是否已经回写！", 2);
            return;
        }
        //发送soap消息，并解析结果
        wmsPurchaseMapper.updateWarehouseTransferCallback(warehouseTransferVo.getIndc003(), "erp待返回", 3);
        try {
            warehouseTransferVo.setActionType(Constant.ActionType_I);
            warehouseTransferVo.setIndcdocno(Constant.PMDSDOCNO_1200);
            warehouseTransferVo.setIndcsite(Constant.PMDSSITE_AMA);
            List<WarehouseTransferListReq> warehouseTransferListReqs = BeanUtil.copyToList(transferListVos, WarehouseTransferListReq.class);
            String resMessage = soapXmlUtil.getSoapXml("WarehouseTransfer", "indc_t", "indd_t", warehouseTransferVo, warehouseTransferListReqs);

            //转换为soap消息
            log.info("仓间调拨单回调：{}", resMessage);
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            //调用等待
            if (warehouseTransferListReqs.size() >= 50) {
                Thread.sleep(100 * 1000);
            } else if (warehouseTransferListReqs.size() >= 30) {
                Thread.sleep(60 * 1000);
            } else if (warehouseTransferListReqs.size() >= 10) {
                Thread.sleep(30 * 1000);
            } else if (warehouseTransferListReqs.size() >= 5) {
                Thread.sleep(10 * 1000);
            }
            log.info("仓间调拨单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferCallback(warehouseTransferVo.getIndc003(), xmlResp.getData().get("indcdocno"), 1);
            } else {
                wmsPurchaseMapper.updateWarehouseTransferCallback(warehouseTransferVo.getIndc003(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateWarehouseTransferCallback(warehouseTransferVo.getIndc003(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }

    }

    /**
     * 二阶段调拨拨出单-驻外调拨出库单回调
     */

//    public void transferOutCallback() {
//        //查询没有回调的数据
//        List<TransferOutVo> transferOutVos = wmsPurchaseMapper.getTransferOutCallback();
//
//        List<String> sbillnoList = transferOutVos.stream().map(TransferOutVo::getIndc003).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(sbillnoList)) {
//            return;
//        }
//        //根据没有回调的数据查询明细
//        List<TransferOutListVo> transferOutListVos = wmsPurchaseMapper.getTransferOutListCallback(sbillnoList);
//        Map<String, List<TransferOutListVo>> listMap = transferOutListVos.stream().collect(Collectors.groupingBy(TransferOutListVo::getMoveno));
//        for (TransferOutVo transferOutVo : transferOutVos) {
//            transferOutVo.setActionType(Constant.ActionType_I);
//            transferOutVo.setIndcdocno(Constant.PMDSDOCNO_1202);
//            transferOutVo.setIndcsite(Constant.PMDSSITE_AMA);
//            List<TransferOutListVo> transferOutListVoList = listMap.get(transferOutVo.getIndc003());
//            List<TransferOutListReq> transferOutListReqs = BeanUtil.copyToList(transferOutListVoList, TransferOutListReq.class);
//            String resMessage = soapXmlUtil.getSoapXml("TransferOut", "indc_t", "indd_t", transferOutVo, transferOutListReqs);
//            try {
//                //转换为soap消息
//                MessageFactory msgFactory = MessageFactory.newInstance();
//                SOAPMessage message = msgFactory.createMessage();
//                SOAPPart soapPart = message.getSOAPPart();
//                byte[] buffer = resMessage.getBytes();
//                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
//                StreamSource source = new StreamSource(stream);
//                soapPart.setContent(source);
//                message.writeTo(System.out);
//                log.info(resMessage);
//                log.info("二阶段调拨拨出单-驻外调拨出库单回调：{}", resMessage);
//                //发送soap消息，并解析结果
//                String result = soapXmlUtil.sendSoapMessage(message);
//                log.info("二阶段调拨拨出单-驻外调拨出库单回调: {}", result);
//                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
//                if (xmlResp.getCode().equals("0")) {
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updateWarehouseTransferCallback(transferOutVo.getIndc003(), xmlResp.getData().get("indcdocno"), 1);
//                } else {
//                    wmsPurchaseMapper.updateWarehouseTransferCallback(transferOutVo.getIndc003(), xmlResp.getMessage(), 2);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 二阶调拨拨入过账单回调
     */
//    @Scheduled(cron = "40 0/2 * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 80000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void transferInCallback() {
        //查询没有回调的数据
        TransferInVo transferInVo = wmsPurchaseMapper.getTransferInCallback();

        if (ObjectUtil.isEmpty(transferInVo)) {
            log.info("未查询到二阶段调拨拨入过账单数据，修改过账失败数据重新进行回写");
            wmsPurchaseMapper.transferInCallbackLose();
            return;
        }
        transferInVo.setActionType(Constant.ActionType_I);
        transferInVo.setIndcsite(Constant.PMDSSITE_AMA);
        Class<PurchaseReceiptFormVoReq> target = PurchaseReceiptFormVoReq.class;
        BeanUtils.copyProperties(transferInVo, target);

        String resMessage = soapXmlUtil.getSoapXml("TransferIn", "indc_t", transferInVo);
        try {

            //转换为soap消息
            log.info("二阶段调拨拨入过账单回调：{}", resMessage);
            wmsPurchaseMapper.updateWarehouseTransferInCallback(transferInVo.getIndcdocno(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("二阶段调拨拨入过账单回调返回结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferInCallback(transferInVo.getIndcdocno(), xmlResp.getData().get("indcdocno"), 1);
            } else {
                wmsPurchaseMapper.updateWarehouseTransferInCallback(transferInVo.getIndcdocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateWarehouseTransferInCallback(transferInVo.getIndcdocno(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    /**
     * 工单发出的接口
     *
     * @param orderNo 领料单单号
     */
    public void workOrderIssue(String orderNo) {
        WorkOrderIssueVo workOrderIssueVo = wmsPurchaseMapper.getWorkOrderIssue(orderNo);
        if (ObjectUtils.isEmpty(workOrderIssueVo)) {
            return;
        }

        WorkOrderIssueReq workOrderIssueReq = BeanUtil.toBean(workOrderIssueVo, WorkOrderIssueReq.class);
        workOrderIssueReq.setUser(workOrderIssueVo.getUserNO());
        String resMessage = soapXmlUtil.getSoapXml("WorkOrderIssue", "sfaa_t", workOrderIssueReq);
        try {
            //转换为soap消息
            log.info("soap工单发出接口回调->{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("soap工单发出接口回调返回->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                wmsPurchaseMapper.insertWorkOrderIssue(workOrderIssueVo, xmlResp.getCode(), xmlResp.getData().get("sfaadocno"));
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.insertWorkOrderIssue(workOrderIssueVo, xmlResp.getCode(), xmlResp.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生产工单（领料单）
     */

//    @Scheduled(cron = "0 0/1 * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 21 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void pickingOutCallback() {
        //查询没有回调的数据
        PickingOutVo pickingOutVo = wmsPurchaseMapper.getPickingOutCallback();
//        List<String> outnoList = pickingOutCallback.stream().map(PickingOutVo::getSfda014).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(pickingOutVo)) {
            log.info("未查询到生产工单（领料单）数据，修改过账失败数据重新进行回写");
            wmsPurchaseMapper.pickingOutCallbackLose();
            return;
        }
        //直接修改状态为带返回避免下次查询到数据
        log.info("查询出的生产领料单->{}", JSONObject.toJSONString(pickingOutVo));
        //捕获异常，设置单据状态为失败，避免总是取到该单据导致后续任务无法处理
        //根据没有回调的数据查询细表
        List<PickingOutVoReceiptListVo> pickingOutVoReceiptList = wmsPurchaseMapper.getPickingOutReceiptListCallback(pickingOutVo.getSfda014(), pickingOutVo.getSbillno(), pickingOutVo.getSfda004());
        if (CollUtil.isEmpty(pickingOutVoReceiptList)) {
            log.info("查询出的生产领料单明细信息为空->{}", JSONObject.toJSONString(pickingOutVo));
            wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), "查询出的生产领料单明细信息为空", 2);
            return;
        }
        List<String> stringList = pickingOutVoReceiptList.stream().map(PickingOutVoReceiptListVo::getSfdc001).collect(Collectors.toList());
        if (!stringList.contains(pickingOutVo.getSbillno())) {
            log.info("明细出库工单与住表出库工单不一致");
            log.info("查询出的生产领料单信息->{}", JSONObject.toJSONString(pickingOutVo));
            log.info("查询出的生产领料单明细信息->{}", JSONObject.toJSONString(pickingOutVoReceiptList));
            return;
        }
        //优先占用防止计算逻辑再次查询到该工单
        wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), "erp待返回", 3);
        try {

//            Map<String, List<PickingOutVoReceiptListVo>> listMap = pickingOutVoReceiptList.stream().collect(Collectors.groupingBy(PickingOutVoReceiptListVo::getOutno));

//            for (PickingOutVo pickingOutVo : pickingOutCallback) {
            //工单发出回调
            this.workOrderIssue(pickingOutVo.getSfda014());
            pickingOutVo.setActionType(Constant.ActionType_I);
            pickingOutVo.setSfdadocno(Constant.PMDSDOCNO_5409);
            pickingOutVo.setSfdasite(Constant.PMDSSITE_AMA);
//                List<PickingOutVoReceiptListVo> pickingOutVoReceiptListVoList = listMap.get(pickingOutVo.getSfda014());
            List<PickingOutVoReceiptListReq> pickingOutVoReceiptListReqs = BeanUtil.copyToList(pickingOutVoReceiptList, PickingOutVoReceiptListReq.class);
            //分发项次项序  返回要修改的数据
            if (ObjectUtil.isEmpty(pickingOutVoReceiptListReqs)) {
                log.info("非常见的数据处理问题，请联系开发人员处理", pickingOutVo.getSfda014());
                wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), "非常见的数据处理问题，请联系开发人员处理", 2);
                return;
            }
            List<AsyncWorkorderVo> asyncWorkorderVos = distributeItemOrder(pickingOutVoReceiptListReqs, pickingOutVo.getSfda014());
            log.info(pickingOutVoReceiptListReqs.toString());
            if (CollUtil.isEmpty(asyncWorkorderVos)) {
                log.info("未获取到出库单工单信息跳出本次循环:出库单号:{}", pickingOutVo.getSfda014());
                return;
            } else {
                //查询库存管理特征
                for (PickingOutVoReceiptListReq pickingOutVoReceiptListReq : pickingOutVoReceiptListReqs) {
                    String inag003 = wmsPurchaseMapper.getInventoryInag003(pickingOutVoReceiptListReq);
                    if (ObjectUtil.isNotEmpty(inag003)) {
                        pickingOutVoReceiptListReq.setSfdc016(inag003);
                    }
                }
            }
            String resMessage = soapXmlUtil.getSoapXml("ReGetMaterial", "sfda_t", "sfdc_t", pickingOutVo, pickingOutVoReceiptListReqs);
            //转换为soap消息
            log.info("生产领料回写数据:{}", resMessage);
            //状态处理为erp待返回
            wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            //调用等待
//            if (pickingOutVoReceiptListReqs.size() >= 50) {
//                Thread.sleep(60 * 1000);
//            } else if (pickingOutVoReceiptListReqs.size() >= 30) {
//                Thread.sleep(30 * 1000);
//            } else if (pickingOutVoReceiptListReqs.size() >= 10) {
//                Thread.sleep(10 * 1000);
//            } else if (pickingOutVoReceiptListReqs.size() >= 5) {
//                Thread.sleep(5 * 1000);
//            }
            log.info("soap接口生产领料回调->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), xmlResp.getData().get("sfdadocno"), 1);
                //更新工单表数据
                asyncWorkorderMapper.updateBatch(asyncWorkorderVos);
                //新增记录数据
                newRecordData(pickingOutVo.getSfda014(), pickingOutVoReceiptListReqs);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateReGetMaterialCallback(pickingOutVo.getSfda014(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    private void newRecordData(String orderno, List<PickingOutVoReceiptListReq> pickingOutVoReceiptListReqs) {
        List<BackRecordVo> backRecordVoList = new ArrayList<>();
        for (PickingOutVoReceiptListReq pickingOutVoReceiptListReq : pickingOutVoReceiptListReqs) {
            BackRecordVo backRecordVo = new BackRecordVo();
            backRecordVo.setWorkno(pickingOutVoReceiptListReq.getSfdc001());
            backRecordVo.setItem(pickingOutVoReceiptListReq.getSfdc002());
            backRecordVo.setTerm(pickingOutVoReceiptListReq.getSfdc003());
            backRecordVo.setMcode(pickingOutVoReceiptListReq.getSfdc004());
            backRecordVo.setNum(pickingOutVoReceiptListReq.getSfdc007());
            backRecordVo.setOrderno(orderno);
            backRecordVo.setBatchno(pickingOutVoReceiptListReq.getSfdc014());
            backRecordVoList.add(backRecordVo);
        }
        if (CollUtil.isNotEmpty(backRecordVoList)) {
            asyncWorkorderMapper.saveBatchBackRecord(backRecordVoList);
        }
    }

    private List<AsyncWorkorderVo> distributeItemOrder(List<PickingOutVoReceiptListReq> pickingOutVoReceiptListReqs, String outno) {
        //查询
        //获取工单号
        String workOrderNo = pickingOutVoReceiptListReqs.get(0).getSfdc001();
        List<String> mcodeList = pickingOutVoReceiptListReqs.stream().map(PickingOutVoReceiptListReq::getSfdc004).distinct().collect(Collectors.toList());

        //每次都重新获取下工单信息，发料和已发，避免工单变更造成未及时获取到最新领料需求
        //1、基于工单先删除原有的数据 以下存储过程中有删除数据这里不需要删除
//        asyncWorkorderMapper.deleteByWordOrderNo(workOrderNo);
        //2、拉取工单信息到async_workorder
        asyncWorkorderMapper.updateAsyncWorkorder(workOrderNo);

        //查询工单是否存在
        String asyncWorkorder = asyncWorkorderMapper.getAsyncWorkorder(workOrderNo);
        if (ObjectUtil.isEmpty(asyncWorkorder)) {
            log.error("单号工单信息未查到:{}", workOrderNo);
            wmsPurchaseMapper.updateReGetMaterialCallback(outno, "未获取到出库单工单信息，工单可能已结案或已删除", 2);
            return null;
        }
        Map<String, List<PickingOutVoReceiptListReq>> mcodeListMap = pickingOutVoReceiptListReqs.stream().collect(Collectors.groupingBy(PickingOutVoReceiptListReq::getSfdc004));
        for (Map.Entry<String, List<PickingOutVoReceiptListReq>> entry : mcodeListMap.entrySet()) {
            String mcode = entry.getKey();

            List<PickingOutVoReceiptListReq> entryValue = entry.getValue();
            BigDecimal mcodeNum = entryValue.stream().map(PickingOutVoReceiptListReq::getSfdc007).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (mcodeNum.compareTo(BigDecimal.ZERO) <= 0) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReGetMaterialCallback(outno, "料号" + mcode + "发料数量为0！本出库单未回写，请确认！", 2);
                return null;
            }
            BigDecimal asyncWorkorderMnum = asyncWorkorderMapper.getAsyncWorkorderMnum(workOrderNo, mcode);
            if (ObjectUtil.isEmpty(asyncWorkorderMnum)) {
                wmsPurchaseMapper.updateReGetMaterialCallback(outno, "料号" + mcode + "在该工单中未查到！本出库单未回写，请确认！", 2);
                return null;
            }
            //本次发料总数量小于剩余发料总数量不会写直接报错
            log.info("料号:{},本次发料数量:{},单据剩余发料数量:{}", mcode, mcodeNum, asyncWorkorderMnum);
            if (mcodeNum.compareTo(asyncWorkorderMnum) > 0) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReGetMaterialCallback(outno, "料号" + mcode + ",本次发料数量:" + mcodeNum + ",单据剩余发料数量:" + asyncWorkorderMnum, 2);
                return null;
            }
        }
        //获取工单信息
        List<AsyncWorkorderVo> distributeItemOrder = asyncWorkorderMapper.getDistributeItemOrder(workOrderNo, mcodeList);
        if (CollUtil.isEmpty(distributeItemOrder)) {
            //更新相应表状态为已下发
            wmsPurchaseMapper.updateReGetMaterialCallback(outno, workOrderNo + "工单发料数据已足够！本出库单未回写，请确认！", 2);
            return null;
        }
        List<PickingOutVoReceiptListReq> newPickingOutVoReceiptListReqs = new ArrayList<>();
        //分发工单信息
        for (PickingOutVoReceiptListReq pickingOutVoReceiptListReq : pickingOutVoReceiptListReqs) {
            //料号
            String sfdc004 = pickingOutVoReceiptListReq.getSfdc004();
            //数量
            BigDecimal sfdc007 = pickingOutVoReceiptListReq.getSfdc007();
            for (AsyncWorkorderVo asyncWorkorderVo : distributeItemOrder) {
                if (sfdc007.compareTo(BigDecimal.ZERO) == 0) {
                    break;
                }
                //料号相同时
                if (asyncWorkorderVo.getMcode().equals(sfdc004) && asyncWorkorderVo.getTotal().compareTo(asyncWorkorderVo.getNum()) > 0) {
                    //项次数量足够
                    if (asyncWorkorderVo.getTotal().compareTo(sfdc007.add(asyncWorkorderVo.getNum())) >= 0 && ObjectUtil.isEmpty(pickingOutVoReceiptListReq.getSfdc002())) {
                        asyncWorkorderVo.setNum(sfdc007.add(asyncWorkorderVo.getNum()));
                        //项次
                        pickingOutVoReceiptListReq.setSfdc002(asyncWorkorderVo.getItem());
                        //项序
                        pickingOutVoReceiptListReq.setSfdc003(asyncWorkorderVo.getTerm());
                        sfdc007 = BigDecimal.ZERO;
                        //领完数量不够时寻找下一个项次
                    } else {
                        //已经有项次时 获取下一个项次
                        if (ObjectUtil.isNotEmpty(pickingOutVoReceiptListReq.getSfdc002())) {
                            //剩余数量大于0 创建出一个新的出库单
                            if (sfdc007.compareTo(BigDecimal.ZERO) > 0) {
                                PickingOutVoReceiptListReq newReq = BeanUtil.copyProperties(pickingOutVoReceiptListReq, PickingOutVoReceiptListReq.class);
                                newReq.setSfdc007(sfdc007);
                                //项次
                                newReq.setSfdc002(asyncWorkorderVo.getItem());
                                //项序
                                newReq.setSfdc003(asyncWorkorderVo.getTerm());
                                if (asyncWorkorderVo.getTotal().compareTo(sfdc007.add(asyncWorkorderVo.getNum())) >= 0) {
                                    newReq.setSfdc007(sfdc007);
                                    asyncWorkorderVo.setNum(sfdc007.add(asyncWorkorderVo.getNum()));
                                    sfdc007 = BigDecimal.ZERO;
                                } else {
                                    //项次剩余要领取数量
                                    BigDecimal subtract = asyncWorkorderVo.getTotal().subtract(asyncWorkorderVo.getNum());
                                    newReq.setSfdc007(subtract);
                                    asyncWorkorderVo.setNum(asyncWorkorderVo.getTotal());
                                    //出库剩余数量
                                    sfdc007 = sfdc007.subtract(subtract);
                                }
                                newPickingOutVoReceiptListReqs.add(newReq);
                            }
                        } else {
                            //剩余要领取数量
                            BigDecimal subtract = asyncWorkorderVo.getTotal().subtract(asyncWorkorderVo.getNum());
                            asyncWorkorderVo.setNum(asyncWorkorderVo.getTotal());
                            //项次
                            pickingOutVoReceiptListReq.setSfdc002(asyncWorkorderVo.getItem());
                            //项序
                            pickingOutVoReceiptListReq.setSfdc003(asyncWorkorderVo.getTerm());
                            pickingOutVoReceiptListReq.setSfdc007(subtract);
                            //出库剩余数量
                            sfdc007 = sfdc007.subtract(subtract);
                        }
                    }
                }
            }
        }

        if (CollUtil.isNotEmpty(newPickingOutVoReceiptListReqs)) {
            pickingOutVoReceiptListReqs.addAll(newPickingOutVoReceiptListReqs);
        }

        //清除小于0的数据
        return distributeItemOrder.stream().filter(item -> item.getNum().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
    }

    /**
     * 生产工单（退料单）
     */
//    @Scheduled(fixedDelay = 180 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void returnInCallback() {
        //查询没有回调的数据
        ReturnInVo returnInVo = wmsPurchaseMapper.getReturnInCallback();
//        List<String> innoList = returnInCallback.stream().map(ReturnInVo::getSfda014).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(returnInVo)) {
            log.info("未查询到生产工单（退料单）数据，修改失败单据重新回写");
            wmsPurchaseMapper.returnInCallbackLose();
            return;
        }
        //根据没有回调的数据查询细表
        List<ReturnInReceiptListVo> returnInReceiptListVos = wmsPurchaseMapper.getReturnInReceiptListCallback(returnInVo.getSfda014());
//        Map<String, List<ReturnInReceiptListVo>> listMap = returnInReceiptList.stream().collect(Collectors.groupingBy(ReturnInReceiptListVo::getInno));
//        for (ReturnInVo returnInVo : returnInCallback) {
        try {
            returnInVo.setActionType(Constant.ActionType_I);
            returnInVo.setSfdadocno(Constant.PMDSDOCNO_5430);
            returnInVo.setSfdasite(Constant.PMDSSITE_AMA);
//            List<ReturnInReceiptListVo> returnInReceiptListVos = listMap.get(returnInVo.getSfda014());

            //获取生产工单可用的项次和相序，退料后ERP会在生产工单备料明细扣减已发数量，后续可以继续领料，我们这边走生产补料，不限制数量，补料需要回填ERP
            List<ReturnInReceiptListVo> returnInReceiptListVoReqs = assembleMorderAutoidAndSequence(returnInReceiptListVos, returnInVo.getSfda014());
            if (CollUtil.isEmpty(returnInReceiptListVoReqs)) {
                wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), "计算工单项次异常请联系开发人员处理", 2);
            }
//                List<ReturnInReceiptListVoReq> returnInReceiptListVoReqs = BeanUtil.copyToList(returnInReceiptListVos, ReturnInReceiptListVoReq.class);
            String resMessage = soapXmlUtil.getSoapXml("ReBackMaterial", "sfda_t", "sfdc_t", returnInVo, returnInReceiptListVoReqs);

            //转换为soap消息
            log.info("生产退料回调:{}", resMessage);

            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("soap接口生产退料回调->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), xmlResp.getData().get("sfdadocno"), 1);
                //更新erp工单发料信息
                asyncWorkorderMapper.updateAsyncWorkorder(returnInReceiptListVoReqs.get(0).getSfdc001());
                //更新wms工单发料信息
                for (ReturnInReceiptListVo returnInReceiptListVo : returnInReceiptListVos) {
                    asyncWorkorderMapper.updateWmsPoLead(returnInReceiptListVo);
                }

            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            wmsPurchaseMapper.updateReBackMaterialCallback(returnInVo.getSfda014(), "非常见的数据处理问题，请联系开发人员处理", 2);
        }
//        }
    }

    private List<ReturnInReceiptListVo> assembleMorderAutoidAndSequence(List<ReturnInReceiptListVo> returnInReceiptListVos, String sfda014) {
        List<ReturnInReceiptListVo> reqList = new ArrayList<>();
        for (ReturnInReceiptListVo returnInReceiptListVo : returnInReceiptListVos) {
            List<AsyncWorkorderVo> asyncWorkorderVos = wmsPurchaseMapper.getWOrkOrderReq(returnInReceiptListVo);
            if (CollUtil.isNotEmpty(asyncWorkorderVos)) {
                BigDecimal sfdc007 = returnInReceiptListVo.getSfdc007();
                for (AsyncWorkorderVo asyncWorkorderVo : asyncWorkorderVos) {
                    ReturnInReceiptListVo copiedProperties = BeanUtil.copyProperties(returnInReceiptListVo, ReturnInReceiptListVo.class);
                    copiedProperties.setSfdc002(asyncWorkorderVo.getItem());
                    copiedProperties.setSfdc003(asyncWorkorderVo.getTerm());
                    //数量大于等于发出数量
                    if (sfdc007.compareTo(asyncWorkorderVo.getNum()) >= 0) {
                        copiedProperties.setSfdc007(sfdc007);
                        sfdc007 = sfdc007.subtract(asyncWorkorderVo.getNum());
                    } else {
                        copiedProperties.setSfdc007(sfdc007);
                        sfdc007 = BigDecimal.ZERO;
                    }
                    reqList.add(copiedProperties);
                    if (sfdc007.compareTo(BigDecimal.ZERO) == 0) {
                        break;
                    }
                }
            }
        }
        return reqList;
    }

    /**
     * 生产完工入库-成品入库-提交时不自动审核，过账成功后自动审核，做卡控防止数据出现问题
     */
//    @Scheduled(cron = "30 0/2 * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 16 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void completeInCallback() {
        //查询没有回调的数据
        CompleteInVo completeInVo = wmsPurchaseMapper.getCompleteInCallback();
//        List<String> innoList = completeInCallback.stream().map(CompleteInVo::getSfeaud005).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(completeInVo) || ObjectUtils.isEmpty(completeInVo.getSfeaud005())) {
            log.info("未查询到生产完工入库数据，修改错误单据重试");
            wmsPurchaseMapper.completeInCallbackLose();
            return;
        }

        //捕获异常，设置单据状态为失败，避免总是取到该单据导致后续任务无法处理
        try {
            String sfeaud005 = completeInVo.getSfeaud005();
            //根据没有回调的数据查询细表
            List<CompleteInVoReceiptListVo> completeInVoReceiptList = wmsPurchaseMapper.getCompleteInReceiptListCallback(sfeaud005);
            Map<String, List<CompleteInVoReceiptListVo>> listMap = completeInVoReceiptList.stream().collect(Collectors.groupingBy(CompleteInVoReceiptListVo::getInno));
//        for (CompleteInVo completeInVo : completeInCallback) {
            completeInVo.setActionType(Constant.ActionType_I);
            completeInVo.setSfeadocno(Constant.PMDSDOCNO_5701);
            completeInVo.setSfeasite(Constant.PMDSSITE_AMA);
            List<CompleteInVoReceiptListVo> completeInVoReceiptListVos = listMap.get(completeInVo.getSfeaud005());
            List<CompleteInVoReceiptListReq> completeInVoReceiptListReqs = BeanUtil.copyToList(completeInVoReceiptListVos, CompleteInVoReceiptListReq.class);
            //查询工单已入回填数量
            String sfeb001 = completeInVoReceiptListReqs.get(0).getSfeb001();

            int completeInCallbackRunCard = wmsPurchaseMapper.getCompleteInCallbackRunCard(sfeb001);
            //老数据按erp现在的项次计算
            Integer completeInCallbackRunCardInno = wmsPurchaseMapper.getCompleteInCallbackRunCardInno(completeInVo.getSfeaud005());
            if (ObjectUtil.isNotEmpty(completeInCallbackRunCardInno) && completeInCallbackRunCardInno != 0) {
                completeInCallbackRunCard = completeInCallbackRunCardInno;
            }

            //封装runcard
//            for (int i = 0; i < completeInVoReceiptListReqs.size(); i++) {
//                completeInVoReceiptListReqs.get(i).setSfeb026(completeInCallbackRunCard + i);
//            }
            for (CompleteInVoReceiptListReq completeInVoReceiptListReq : completeInVoReceiptListReqs) {
                //根据批号截取项次
                completeInCallbackRunCard++;
                completeInVoReceiptListReq.setSfeb026(completeInCallbackRunCard);
            }

            String resMessage = soapXmlUtil.getSoapXml("WorkOrderin", "sfea_t", "sfeb_t", completeInVo, completeInVoReceiptListReqs);
            try {
                //转换为soap消息
                log.info("生产完工入库请求数据->{}", resMessage);

                //发送soap消息，并解析结果
                //修改状态为3 erp待返回
                wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), "数据反写中", 3);
                String result;
                try {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                } catch (Exception e) {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                }
                //调用等待
                if (completeInVoReceiptListReqs.size() >= 50) {
                    Thread.sleep(120 * 1000);
                } else if (completeInVoReceiptListReqs.size() >= 30) {
                    Thread.sleep(60 * 1000);
                } else if (completeInVoReceiptListReqs.size() >= 10) {
                    Thread.sleep(30 * 1000);
                } else if (completeInVoReceiptListReqs.size() >= 5) {
                    Thread.sleep(15 * 1000);
                }
                log.info("soap接口生产完工回调->{}", result);
                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                if (xmlResp.getCode().equals("0")) {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), xmlResp.getData().get("sfeadocno"), 1);
                    //更新入库单状态信息
                    wmsPurchaseMapper.updateStInstoreCp(completeInVo.getSfeaud005());
                } else {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), xmlResp.getMessage(), 2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        }
        } catch (Exception e) {
            wmsPurchaseMapper.updateWorkOrderinCallback(completeInVo.getSfeaud005(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }


    }

//    @Scheduled(cron = "35 0/1 * * * ?")//开启定时同步
//    @Async(value = "taskExecutor")
//    public void otherInWarehousingCallback() {
//        //查询没有回调的数据
//        List<OtherInWarehousingVo> otherInWarehousingCallback = wmsPurchaseMapper.getOtherInWarehousingCallback();
//        List<String> innoList = otherInWarehousingCallback.stream().map(OtherInWarehousingVo::getInba006).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(innoList)) {
//            return;
//        }
//        //根据没有回调的数据查询细表
//        List<OtherInWarehousingListVo> returnInReceiptList = wmsPurchaseMapper.getOtherInWarehousingListCallback(innoList);
//        Map<String, List<OtherInWarehousingListVo>> listMap = returnInReceiptList.stream().collect(Collectors.groupingBy(OtherInWarehousingListVo::getInno));
//        for (OtherInWarehousingVo otherInWarehousingVo : otherInWarehousingCallback) {
//            otherInWarehousingVo.setActionType(Constant.ActionType_I);
//            otherInWarehousingVo.setInbadocno(Constant.PMDSDOCNO_1002);
//            otherInWarehousingVo.setInbasite(Constant.PMDSSITE_AMA);
//            List<OtherInWarehousingListVo> otherInWarehousingListVo = listMap.get(otherInWarehousingVo.getInba006());
//            List<OtherInWarehousingListVoReq> otherInWarehousingListVoReq = BeanUtil.copyToList(otherInWarehousingListVo, OtherInWarehousingListVoReq.class);
//            String resMessage = soapXmlUtil.getSoapXml("MiscellaneousIn", "inba_t", "inbb_t", otherInWarehousingVo, otherInWarehousingListVoReq);
//            try {
//                //转换为soap消息
//                MessageFactory msgFactory = MessageFactory.newInstance();
//                SOAPMessage message = msgFactory.createMessage();
//                SOAPPart soapPart = message.getSOAPPart();
//                byte[] buffer = resMessage.getBytes();
//                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
//                StreamSource source = new StreamSource(stream);
//                soapPart.setContent(source);
//                message.writeTo(System.out);
    //log.info(resMessage);
//
//                //发送soap消息，并解析结果
//                String result = soapXmlUtil.sendSoapMessage(message);
//                log.info("soap接口其它入库回调->{}", result);
//                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
//                if (xmlResp.getCode().equals("0")) {
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updateOtherInWarehousingCallback(otherInWarehousingVo.getInba006(), xmlResp.getData().get("inbadocno"), 1);
//                } else {
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updateOtherInWarehousingCallback(otherInWarehousingVo.getInba006(), xmlResp.getMessage(), 2);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 其他出库回填
     */
//    @Scheduled(cron = "40 0/1 * * * ?")//开启定时同步
//    @Async(value = "taskExecutor")
//    public void otherOutWarehouseCallback() {
//        //查询没有回调的数据
//        List<OtherOutWarehouseVo> otherOutWarehouseCallback = wmsPurchaseMapper.getOtherOutWarehousingCallback();
//        List<String> outnoList = otherOutWarehouseCallback.stream().map(OtherOutWarehouseVo::getInba006).collect(Collectors.toList());
//        if (ObjectUtils.isEmpty(outnoList)) {
//            return;
//        }
//        //根据没有回调的数据查询细表
//        List<OtherOutWarehouseListVo> returnInReceiptList = wmsPurchaseMapper.getOtherOutWarehousingListCallback(outnoList);
//        Map<String, List<OtherOutWarehouseListVo>> listMap = returnInReceiptList.stream().collect(Collectors.groupingBy(OtherOutWarehouseListVo::getOutno));
//        for (OtherOutWarehouseVo otherOutWarehouseVo : otherOutWarehouseCallback) {
//            otherOutWarehouseVo.setActionType(Constant.ActionType_I);
//            otherOutWarehouseVo.setInbadocno(Constant.PMDSDOCNO_1104);
//            otherOutWarehouseVo.setInbasite(Constant.PMDSSITE_AMA);
//            List<OtherOutWarehouseListVo> otherOutWarehouseListVo = listMap.get(otherOutWarehouseVo.getInba006());
//            List<OtherOutWarehouseListVoReq> otherOutWarehouseListVoReq = BeanUtil.copyToList(otherOutWarehouseListVo, OtherOutWarehouseListVoReq.class);
//            String resMessage = soapXmlUtil.getSoapXml("MiscellaneousOut", "inba_t", "inbb_t", otherOutWarehouseVo, otherOutWarehouseListVoReq);
//            try {
//                //转换为soap消息
//                MessageFactory msgFactory = MessageFactory.newInstance();
//                SOAPMessage message = msgFactory.createMessage();
//                SOAPPart soapPart = message.getSOAPPart();
//                byte[] buffer = resMessage.getBytes();
//                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
//                StreamSource source = new StreamSource(stream);
//                log.info("soap接口其他出库回调->{}", source);
//                soapPart.setContent(source);
//                message.writeTo(System.out);
    //log.info(resMessage);
//
//                //发送soap消息，并解析结果
//                String result = soapXmlUtil.sendSoapMessage(message);
//                log.info("soap接口其他出库回调->{}", result);
//                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
//                if (xmlResp.getCode().equals("0")) {
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updateOtherOutWarehouseCallback(otherOutWarehouseVo.getInba006(), xmlResp.getData().get("inbadocno"), 1);
//                } else {
//                    //更新相应表状态为已下发
//                    wmsPurchaseMapper.updateOtherOutWarehouseCallback(otherOutWarehouseVo.getInba006(), xmlResp.getMessage(), 2);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 刪除领料回填ERP
     */
    public void deletePickingOutCallback(String orderNo) {
        DeletePickingOutVo deletePickingOutVo = wmsPurchaseMapper.getDeletePickingOutCallback(orderNo);
        if (ObjectUtils.isEmpty(deletePickingOutVo) || StringUtils.isBlank(deletePickingOutVo.getSfdadocno())) {
            log.info("单据：{}", deletePickingOutVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deletePickingOutVo.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("ReGetMaterial", "sfda_t", deletePickingOutVo);
        try {
            //转换为soap消息
            log.info("删除生产领料数据->{}", resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除生产领料回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReGetMaterialCallback(deletePickingOutVo.getSfda014(), xmlResp.getMessage(), 0);
                //还原回调数据
                List<BackRecord> backRecordByOutno = wmsPurchaseMapper.getBackRecordByOutno(orderNo);
                wmsPurchaseMapper.updateAsyncWorkorderList(backRecordByOutno);
                wmsPurchaseMapper.deleteBackRecord(orderNo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生产退料回填ERP删除
     *
     * @param orderNo
     */
    public void deleteReturnInCallback(String orderNo) {
        DeleteReturnIntVo deleteReturnIntVo = wmsPurchaseMapper.getDeleteReturnInCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteReturnIntVo) || StringUtils.isBlank(deleteReturnIntVo.getSfdadocno())) {
            log.info("单据：{}", deleteReturnIntVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteReturnIntVo.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("ReBackMaterial", "sfda_t", deleteReturnIntVo);
        try {
            //转换为soap消息
            log.info("删除生产退料回调->{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除生产退料回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateReBackMaterialCallback(deleteReturnIntVo.getSfda014(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除完工入库反写ERP
     *
     * @param orderNo
     */
    public void deleteCompleteInCallback(String orderNo) {
        DeleteCompleteInVo deleteCompleteInVo = wmsPurchaseMapper.getDeleteCompleteInCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteCompleteInVo) || StringUtils.isBlank(deleteCompleteInVo.getSfeadocno())) {
            log.info("单据：{}", deleteCompleteInVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteCompleteInVo.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("WorkOrderin", "sfea_t", deleteCompleteInVo);
        try {
            //转换为soap消息
            MessageFactory msgFactory = MessageFactory.newInstance();
            SOAPMessage message = msgFactory.createMessage();
            SOAPPart soapPart = message.getSOAPPart();
            byte[] buffer = resMessage.getBytes();
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
            StreamSource source = new StreamSource(stream);
            soapPart.setContent(source);
            message.writeTo(System.out);
            log.info("删除生产完工入库->{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除生产完工入库回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWorkOrderinCallback(deleteCompleteInVo.getSfeaud005(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 其他出库回填删除
     *
     * @param orderNo
     */
    public void deleteOtherOutWarehouseCallback(String orderNo) {
        DeleteOtherOutWarehouseVo deleteOtherOutWarehouseVo = wmsPurchaseMapper.getDeleteOtherOutWarehouseCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteOtherOutWarehouseVo) || StringUtils.isBlank(deleteOtherOutWarehouseVo.getInbadocno())) {
            log.info("单据：{}", deleteOtherOutWarehouseVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteOtherOutWarehouseVo.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("MiscellaneousOut", "inba_t", deleteOtherOutWarehouseVo);
        try {
            //转换为soap消息
            MessageFactory msgFactory = MessageFactory.newInstance();
            SOAPMessage message = msgFactory.createMessage();
            SOAPPart soapPart = message.getSOAPPart();
            byte[] buffer = resMessage.getBytes();
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
            StreamSource source = new StreamSource(stream);
            soapPart.setContent(source);
            message.writeTo(System.out);
            log.info("删除其他出库回填结果->{}", resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除其他出库回填结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateOtherOutWarehouseCallback(deleteOtherOutWarehouseVo.getInba006(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 其他入库回填删除
     *
     * @param orderNo
     */
    public void deleteOtherInWarehousingCallback(String orderNo) {
        DeleteOtherInWarehouseVo deleteOtherInWarehouseVo = wmsPurchaseMapper.getDeleteOtherInWarehousingCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteOtherInWarehouseVo) || StringUtils.isBlank(deleteOtherInWarehouseVo.getInbadocno())) {
            log.info("单据：{}", deleteOtherInWarehouseVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteOtherInWarehouseVo.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("MiscellaneousIn", "inba_t", deleteOtherInWarehouseVo);
        try {
            log.info(resMessage);
            log.info("删除其他入库回填：{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除其他出库回填结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateOtherInWarehousingCallback(deleteOtherInWarehouseVo.getInba006(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 仓间调拨删除
     *
     * @param orderNo
     */
    public void deleteWarehouseTransferCallback(String orderNo) {
        DeleteWarehouseTransferVo deleteWarehouseTransferVo = wmsPurchaseMapper.getDeleteWarehouseTransferCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteWarehouseTransferVo) || StringUtils.isBlank(deleteWarehouseTransferVo.getIndcdocno())) {
            log.info("单据：{}", deleteWarehouseTransferVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteWarehouseTransferVo.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("WarehouseTransfer", "indc_t", deleteWarehouseTransferVo);
        try {
            //转换为soap消息
            log.info("删除生产退料回调->{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除生产退料回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferCallback(deleteWarehouseTransferVo.getIndc003(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销售出库回调
     */
//    @Scheduled(cron = "0/45 * * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 21 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void sellOutCallback() {
        //查询没有回调的数据
        SellOutCallbackVo sellOutCallbackVo = wmsPurchaseMapper.getSellOutCallback();
        if (ObjectUtils.isEmpty(sellOutCallbackVo.getXmdkud009())) {
            log.info("未获取到销售出库回写数据，修改回写报错数据重新回写");
            wmsPurchaseMapper.sellOutCallbackLose();
            return;
        }

        //捕获异常，设置单据状态为失败，避免总是取到该单据导致后续任务无法处理
        try {
            //根据没有回调的数据查询细表
            List<SellOutListCallbackVo> sellOutListCallback = wmsPurchaseMapper.getSellOutListCallback(Arrays.asList(sellOutCallbackVo.getXmdkud009()));
            //
            sellOutCallbackVo.setActionType(Constant.ActionType_I);
            if (ObjectUtil.isEmpty(sellOutCallbackVo.getInbadocno())) {
                sellOutCallbackVo.setInbadocno(Constant.PMDSDOCNO_2401);
            }
            sellOutCallbackVo.setXmdksite(Constant.PMDSSITE_AMA);
            List<SellOutListCallbackVoReq> sellOutListCallbackVoReqList = BeanUtil.copyToList(sellOutListCallback, SellOutListCallbackVoReq.class);
            String resMessage = soapXmlUtil.getSoapXml("SalesInvoice", "xmdk_t", "xmdl_t", sellOutCallbackVo, sellOutListCallbackVoReqList);
            try {
                //转换为soap消息
                log.info("soap接口销售出库请求报文:{}", resMessage);
                //状态占用
                wmsPurchaseMapper.updateSellOutCallback(sellOutCallbackVo.getXmdkud009(), "erp待返回", 3);
                //发送soap消息，并解析结果
                String result;
                try {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                } catch (Exception e) {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                }
                //调用等待
                if (sellOutListCallbackVoReqList.size() >= 50) {
                    Thread.sleep(100 * 1000);
                } else if (sellOutListCallbackVoReqList.size() >= 30) {
                    Thread.sleep(60 * 1000);
                } else if (sellOutListCallbackVoReqList.size() >= 10) {
                    Thread.sleep(30 * 1000);
                } else if (sellOutListCallbackVoReqList.size() >= 5) {
                    Thread.sleep(10 * 1000);
                }
                log.info("soap接口销售出库回调报文->{}", result);
                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                if (xmlResp.getCode().equals("0")) {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updateSellOutCallback(sellOutCallbackVo.getXmdkud009(), xmlResp.getData().get("xmdkdocno"), 1);
                } else {
                    //更新相应表状态为已下发
                    wmsPurchaseMapper.updateSellOutCallback(sellOutCallbackVo.getXmdkud009(), xmlResp.getMessage(), 2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateSellOutCallback(sellOutCallbackVo.getXmdkud009(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    /**
     * 销售出库回调删除
     */
    public void deleteSellOutCallback(String orderNo) {
        DeleteSellOutCallbackVo deleteSellOutCallback = wmsPurchaseMapper.getDeleteSellOutCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteSellOutCallback) || StringUtils.isBlank(deleteSellOutCallback.getXmdkdocno())) {
            log.info("单据：{}", deleteSellOutCallback);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteSellOutCallback.setActionType(Constant.ActionType_D);
        String resMessage = soapXmlUtil.getSoapXml("SalesInvoice", "xmdk_t", deleteSellOutCallback);
        try {
            //转换为soap消息
            log.info("删除销售出库回调:{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除销售出库回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateSellOutCallback(deleteSellOutCallback.getXmdkud009(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 二阶调拨拨出还原
     *
     * @param orderNo
     */
    public void deleteTransferOutOutCallback(String orderNo) {
        DeleteTransferOutOutCallback deleteSellOutCallback = wmsPurchaseMapper.getDeleteTransferOutOutCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteSellOutCallback) || StringUtils.isBlank(deleteSellOutCallback.getIndc003())) {
            log.info("单据：{}", deleteSellOutCallback);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteSellOutCallback.setActionType(Constant.ActionType_D);
        deleteSellOutCallback.setIndcsite(Constant.PMDSSITE_AMA);
        String resMessage = soapXmlUtil.getSoapXml("TransferOut", "indc_t", deleteSellOutCallback);
        try {
            //转换为soap消息
            MessageFactory msgFactory = MessageFactory.newInstance();
            SOAPMessage message = msgFactory.createMessage();
            SOAPPart soapPart = message.getSOAPPart();
            byte[] buffer = resMessage.getBytes();
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
            StreamSource source = new StreamSource(stream);
            soapPart.setContent(source);
            message.writeTo(System.out);
            log.info("删除二阶调拨拨出回调:{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除二阶调拨拨出回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferCallback(deleteSellOutCallback.getIndc003(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 生产调拨过账回调
     */
//    @Scheduled(cron = "5 0/1 * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 20000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void WarehouseTransferPost() {
        //查询没有回调的数据
        WarehouseTransferPostVo warehouseTransferPost = wmsPurchaseMapper.getWarehouseTransferPost();
//        WarehouseTransferPostVo warehouseTransferPost = new WarehouseTransferPostVo();
        if (ObjectUtils.isEmpty(warehouseTransferPost) || ObjectUtil.isEmpty(warehouseTransferPost.getIndcdocno())) {
            log.info("未获取到生产调拨过账数据，修改回写报错数据重新回写");
            wmsPurchaseMapper.warehouseTransferPostLose();
            return;
        }

        warehouseTransferPost.setIndcsite(Constant.PMDSSITE_AMA);
        String resMessage = soapXmlUtil.getSoapXml("WarehouseTransferPost", "indc_t", "", warehouseTransferPost, null);
        try {
            //转换为soap消息
            log.info("soap生产调拨过账请求报文->{}", resMessage);
//            log.info(resMessage);
            //回写状态修改为 erp未回填
            wmsPurchaseMapper.updateWarehouseTransferPost(warehouseTransferPost.getIndcdocno(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("soap生产调拨过账回调返回报文->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferPost(warehouseTransferPost.getIndcdocno(), xmlResp.getData().get("indcdocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferPost(warehouseTransferPost.getIndcdocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateWarehouseTransferPost(warehouseTransferPost.getIndcdocno(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    /**
     * 二阶调拨拨入还原
     *
     * @param orderNo
     */
    public void deleteTransferInCallback(String orderNo) {
        DeleteTransferInCallback deleteSellOutCallback = wmsPurchaseMapper.getDeleteTransferInCallback(orderNo);
        if (ObjectUtils.isEmpty(deleteSellOutCallback) || StringUtils.isBlank(deleteSellOutCallback.getIndcdocno())) {
            log.info("单据：{}", deleteSellOutCallback);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        deleteSellOutCallback.setActionType(Constant.ActionType_D);
        deleteSellOutCallback.setIndcsite(Constant.PMDSSITE_AMA);
        String resMessage = soapXmlUtil.getSoapXml("TransferIn", "indc_t", deleteSellOutCallback);
        try {
            //转换为soap消息
            log.info("删除二阶调拨拨入回调:{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除二阶调拨拨入回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateWarehouseTransferInCallback(deleteSellOutCallback.getIndcdocno(), xmlResp.getMessage(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 其他(杂项)出库过账
     */
//    @Scheduled(cron = "0/30 * * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 30000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void MiscellaneousPost() {
        //查询没有回调的数据
        MiscellaneousPostVo warehouseTransferPost = wmsPurchaseMapper.getMiscellaneousPost();
//        WarehouseTransferPostVo warehouseTransferPost = new WarehouseTransferPostVo();
        if (ObjectUtils.isEmpty(warehouseTransferPost) || ObjectUtil.isEmpty(warehouseTransferPost.getInbadocno())) {
            log.info("未查询到其他(杂项)出库过账数据，修改报错数据重新过账");
            wmsPurchaseMapper.MiscellaneousPostLose();
            return;
        }
        warehouseTransferPost.setInbasite(Constant.PMDSSITE_AMA);
        String resMessage = soapXmlUtil.getSoapXml("MiscellaneousPost", "inba_t", "", warehouseTransferPost, null);
        try {
            //转换为soap消息

            log.info("soap其他(杂项)出入库过账请求报文->{}", resMessage);

//            log.info(resMessage);
            //状态占用
            wmsPurchaseMapper.updateMiscellaneousPost(warehouseTransferPost.getInbadocno(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("soap其他(杂项)出入库过账回调返回报文->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateMiscellaneousPost(warehouseTransferPost.getInbadocno(), xmlResp.getData().get("inbadocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateMiscellaneousPost(warehouseTransferPost.getInbadocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateMiscellaneousPost(warehouseTransferPost.getInbadocno(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    /**
     * 其他(杂项)出入库过账还原
     */
    public void deleteMiscellaneousPost() {

    }

    /**
     * 二阶调拨拨出过账
     */
//    @Scheduled(cron = "50 0/2 * * * ?")//开启定时同步
//    @Scheduled(fixedDelay = 25000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void TransferOutPost() {
        //查询没有回调的数据
        TransferOutPostVo transferOutPostVo = wmsPurchaseMapper.getTransferOutPost();
//        WarehouseTransferPostVo warehouseTransferPost = new WarehouseTransferPostVo();
        if (ObjectUtils.isEmpty(transferOutPostVo) || ObjectUtil.isEmpty(transferOutPostVo.getIndcdocno())) {
            log.info("未查询到二阶调拨拨出过账数据，修改报错数据重新过账");
            wmsPurchaseMapper.TransferOutPostLose();
            return;
        }

        try {
            transferOutPostVo.setIndcsite(Constant.PMDSSITE_AMA);
            transferOutPostVo.setActionType(Constant.ActionType_I);
            List<TransferOutListVo> transferOutListVos = null;
            //当有不同的批次时传递实际扫描的批次
            Integer count = wmsPurchaseMapper.getTransferOutListCount(transferOutPostVo.getIndcdocno());
            if (count > 0) {
                transferOutListVos = wmsPurchaseMapper.getTransferOutListCallback(transferOutPostVo.getIndcdocno());
            }

            String resMessage = soapXmlUtil.getSoapXml("TransferOutPost", "indc_t", "indd_t", transferOutPostVo, transferOutListVos);

            //转换为soap消息

            log.info("soap二阶调拨出库过账请求报文->{}", resMessage);


            //回写状态修改为 erp未回填
            wmsPurchaseMapper.updateTransferOutPost(transferOutPostVo.getIndcdocno(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            //调用等待
//            if (transferOutListVos.size() >= 50) {
//                Thread.sleep(100 * 1000);
//            } else if (transferOutListVos.size() >= 30) {
//                Thread.sleep(60 * 1000);
//            } else if (transferOutListVos.size() >= 10) {
//                Thread.sleep(30 * 1000);
//            } else if (transferOutListVos.size() >= 5) {
//                Thread.sleep(10 * 1000);
//            }


            log.info("soap二阶调拨出库过账回调返回报文->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateTransferOutPost(transferOutPostVo.getIndcdocno(), xmlResp.getData().get("indcdocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateTransferOutPost(transferOutPostVo.getIndcdocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateTransferOutPost(transferOutPostVo.getIndcdocno(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    /**
     * 销售退货入库
     */
//    @Scheduled(fixedDelay = 25000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void SalesReturns() {
        SalesReturnsVo salesReturns = wmsPurchaseMapper.getSalesReturns();
        if (ObjectUtil.isEmpty(salesReturns) || ObjectUtil.isEmpty(salesReturns.getXmdkdocno())) {
            log.info("未查询到销售退货入库过账数据，修改报错数据重新过账");
            wmsPurchaseMapper.SalesReturnsLose();
            return;
        }

        //捕获异常，设置单据状态为失败，避免总是取到该单据导致后续任务无法处理
        try {
            salesReturns.setXmdksite(Constant.PMDSSITE_AMA);
            salesReturns.setActionType(Constant.ActionType_I);
            //查询明细表
            String xmdkdocno = salesReturns.getXmdkdocno();
            List<SalesReturnsListVo> salesReturnsList = wmsPurchaseMapper.getSalesReturnsList(xmdkdocno);
            String resMessage = soapXmlUtil.getSoapXml("SalesReturnPost", "xmdk_t", "xmdl_t", salesReturns, salesReturnsList);
            //转换为soap消息
            log.info("soap接口销售退货:{}", resMessage);
            //状态占用
            wmsPurchaseMapper.updateSalesReturnsCallback(salesReturns.getXmdkdocno(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            //调用等待
            if (salesReturnsList.size() >= 50) {
                Thread.sleep(100 * 1000);
            } else if (salesReturnsList.size() >= 30) {
                Thread.sleep(60 * 1000);
            } else if (salesReturnsList.size() >= 10) {
                Thread.sleep(30 * 1000);
            } else if (salesReturnsList.size() >= 5) {
                Thread.sleep(10 * 1000);
            }
            log.info("soap接口销售退货回调->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateSalesReturnsCallback(salesReturns.getXmdkdocno(), xmlResp.getData().get("xmdkdocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateSalesReturnsCallback(salesReturns.getXmdkdocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateSalesReturnsCallback(salesReturns.getXmdkdocno(), "非常见的数据处理问题，请联系开发人员处理", 2);
            e.printStackTrace();
        }
    }

    public void deletePurchaseReceiptCallbackByIncomingInspectionTc(String orderNo) {
        String checkno = orderNo;
        DeletePurchaseNotReceiptVo deletePurchaseNotReceiptVo = wmsPurchaseMapper.getDeletePurchaseReceiptCallbackIncomingInspectionTc(orderNo);
        if (ObjectUtils.isEmpty(deletePurchaseNotReceiptVo) || StringUtils.isBlank(deletePurchaseNotReceiptVo.getPmdsdocno())) {
            log.info("单据：{}", deletePurchaseNotReceiptVo);
            throw new RuntimeException("单据不存在或未反写ERP");
        }
        //找到未删除回填记录
        LambdaQueryWrapper<ProcurementDetailsRecode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcurementDetailsRecode::getCheckno, orderNo + "-tc")
                .eq(ProcurementDetailsRecode::getIsDelete, 0);
        List<ProcurementDetailsRecode> procurementDetailsRecodes = procurementDetailsRecodeMapper.selectList(queryWrapper);
        //----------测试逻辑代码---------
        deletePurchaseNotReceiptVo.setActionType(Constant.ActionType_D);
        ProcurementDetailsRecode procurementDetailsRecodeVo = procurementDetailsRecodes.get(0);
        //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
        deletePurchaseNotReceiptVo.setPmds011(procurementDetailsRecodeVo.getPmdl005());
        String resMessage = soapXmlUtil.getSoapXml("PurchaseGet", "pmds_t", deletePurchaseNotReceiptVo);
        try {
            //转换为soap消息
            log.info("删除采购入库送检单单回调结果:{}", resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库送检单单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为未下发
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspectionTc(checkno, xmlResp.getMessage(), 3);
                //反审出库单
                wmsPurchaseMapper.updateInstoreByCheckNo(checkno, "1");
                //删除出库单
                wmsPurchaseMapper.deleteInstoreByCheckNo(checkno, "1");
//                for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
//                    //更新采购明细已填数量，已回填数量取反再新增就是减
//                    procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
//                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
//                    //删除回填记录
//                    procurementDetailsRecodeMapper.updateProcurementDetailsRecodeToDelete(procurementDetailsRecode);
//
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deletePurchaseReceiptCallbackByIncomingInspectionByNo(String orderNo, String erpNo) {

        DeletePurchaseNotReceiptVo deletePurchaseNotReceiptVo = new DeletePurchaseNotReceiptVo();
        //找到未删除回填记录
        LambdaQueryWrapper<ProcurementDetailsRecode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProcurementDetailsRecode::getCheckno, orderNo)
                .eq(ProcurementDetailsRecode::getIsDelete, 0);
        List<ProcurementDetailsRecode> procurementDetailsRecodes = procurementDetailsRecodeMapper.selectList(queryWrapper);
        deletePurchaseNotReceiptVo.setPmdsdocno(erpNo);
        deletePurchaseNotReceiptVo.setPmds055(orderNo);
        //----------测试逻辑代码---------
        deletePurchaseNotReceiptVo.setActionType(Constant.ActionType_D);
        ProcurementDetailsRecode procurementDetailsRecodeVo = procurementDetailsRecodes.get(0);
        //采购性质：pmdl005 ：采购性质(1:一般采购,2:委外采购)
        deletePurchaseNotReceiptVo.setPmds011(procurementDetailsRecodeVo.getPmdl005());
        String resMessage = soapXmlUtil.getSoapXml("PurchaseGet", "pmds_t", deletePurchaseNotReceiptVo);
        try {
            //转换为soap消息
            log.info(resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库送检单单回调结果: {}", result);
//            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
//            if (xmlResp.getCode().equals("0")) {
//                //更新相应表状态为未下发
//                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(deletePurchaseNotReceiptVo.getPmds055(), xmlResp.getMessage(), 0);
//
//
//                for (ProcurementDetailsRecode procurementDetailsRecode : procurementDetailsRecodes) {
//                    //更新采购明细已填数量，已回填数量取反再新增就是减
//                    procurementDetailsRecode.setReturnQty(procurementDetailsRecode.getReturnQty().negate());
//                    wmsPurchaseMapper.updateAddProcurementDetails(procurementDetailsRecode);
//                    //删除回填记录
//                    procurementDetailsRecodeMapper.updateProcurementDetailsRecodeToDelete(procurementDetailsRecode);
//
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 其他(杂项)入库过账
     */
    public void MiscellaneousPostIn() {
        //查询没有回调的数据
        MiscellaneousPostVo warehouseTransferPost = wmsPurchaseMapper.getMiscellaneousPostIn();
//        WarehouseTransferPostVo warehouseTransferPost = new WarehouseTransferPostVo();
        if (ObjectUtils.isEmpty(warehouseTransferPost) || ObjectUtil.isEmpty(warehouseTransferPost.getInbadocno())) {
            return;
        }
        warehouseTransferPost.setInbasite(Constant.PMDSSITE_AMA);
        //如果有不同批次的数据则需要回写批次数据
        List<MiscellaneousPostListVo> list = wmsPurchaseMapper.getMiscellaneousPostInList(warehouseTransferPost.getInbadocno());
        String resMessage;
        if(CollUtil.isEmpty(list)){
            resMessage = soapXmlUtil.getSoapXml("MiscellaneousPost", "inba_t", "", warehouseTransferPost, null);
        }else {
            resMessage = soapXmlUtil.getSoapXml("MiscellaneousPost", "inba_t", "inbb_t", warehouseTransferPost, list);
        }

        try {
            //转换为soap消息

            log.info("soap其他(杂项)入库过账请求报文->{}", resMessage);

//            log.info(resMessage);
            //状态占用
            wmsPurchaseMapper.updateMiscellaneousPostIn(warehouseTransferPost.getInbadocno(), "erp待返回", 3);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("soap其他(杂项)出入库过账回调返回报文->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateMiscellaneousPostIn(warehouseTransferPost.getInbadocno(), xmlResp.getData().get("inbadocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updateMiscellaneousPostIn(warehouseTransferPost.getInbadocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            wmsPurchaseMapper.updateMiscellaneousPostIn(warehouseTransferPost.getInbadocno(), "非常见的数据处理问题，请联系开发人员处理", 2);
        }
    }

    /**
     * 物料冻结
     */
//    @Scheduled(fixedDelay = 120 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void CodeHoldcnt() {
        CodeHoldcntVo codeHoldcntVo = wmsPurchaseMapper.getCodeHoldcnt();
        if (ObjectUtil.isEmpty(codeHoldcntVo) || ObjectUtil.isEmpty(codeHoldcntVo.getImaa001())) {
            return;
        }
        String resMessage = soapXmlUtil.getSoapXml("CodeHoldcnt", "imaa_t", codeHoldcntVo);
        try {
            //转换为soap消息
            log.info(resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            log.info("料件批次冻结返回->{}", JSONObject.toJSONString(xmlResp));
            if (xmlResp.getCode().equals("0")) {
                //保存进erp数据表
                wmsPurchaseMapper.updateCpbarcodelistDj(codeHoldcntVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 采购仓退
     */
//    @Scheduled(fixedDelay = 210 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void PurchaseBackPost() {
        PurchaseBackPostVo purchaseBackPost = wmsPurchaseMapper.getPurchaseBackPost();
        if (ObjectUtil.isEmpty(purchaseBackPost) || ObjectUtil.isEmpty(purchaseBackPost.getPmdsdocno())) {
            return;
        }
        purchaseBackPost.setPmdssite(Constant.PMDSSITE_AMA);
        String resMessage = soapXmlUtil.getSoapXml("PurchaseBackPost", "pmds_t", purchaseBackPost);
        try {
            //转换为soap消息
            log.info(resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            log.info("采购仓退返回->{}", JSONObject.toJSONString(xmlResp));
            if (xmlResp.getCode().equals("0")) {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updatePurchaseBackPost(purchaseBackPost.getPmdsdocno(), xmlResp.getData().get("pmdsdocno"), 1);
            } else {
                //更新相应表状态为已下发
                wmsPurchaseMapper.updatePurchaseBackPost(purchaseBackPost.getPmdsdocno(), xmlResp.getMessage(), 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}